Rodhos Soft

備忘録を兼ねた技術的なメモです。Rofhos SoftではiOSアプリ開発を中心としてAndroid, Webサービス等の開発を承っております。まずはご相談下さい。

Vue.JS ABC勉強ノート

基本

<template>
</template>

<script>
</script>

<style>
</style>

プラグインを各種使う

Vue.config.productionTip = false

new Vue({
  router,
  vuetify,
  render: h => h(App)
}).$mount('#app')

アプリのマウント

new Vue({
  el: '#app` // エレメントのid指定
})

this.$elでマウントしたタグが見れる。

スクリプト部分の雛形

<script>
/* eslint-disable */
import { defineComponent, computed, watch } from '@vue/composition-api';
import MyCard from '@/components/MyCard.vue';
import Vue from 'vue'

export let bus = new Vue();// イベントバス用

export default defineComponent({
  name: 'Hoge',
  components: { 'my-cards': MyCard },

// データ コンポーネントではデータ側は関数をかえすものとすべき。
  data: function() {
    return {
      name: '未設定',
      myTableData: [
        { title: 'title1', value: 'value1' },
        { title: 'title2', value: 'valueHoge' }
      ],
  },

// ライフサイクル
  created: function() {
    // イベントバス登録
    bus.$on("BusEvent", function (message) {
      alert(message);
    })
  },
  mounted: function() {
    console.log(this.$el); // マウントしているタグを出力
    console.log(this.$refs.hello); // helloのrefのついているタグを参照
  },



// メソッド
  methods: {
    pushCrick: function() {
      this.name = 'poi!';
    },
    pushHome: function() {
      this.$router.push('/');
    },
    addHoge: function() {
      this.myTableData.push({ title: 'HOGE!', value: 'HogeHoge!' });
    },
  },
// 算出プロパティ setter, getterも設置できる。
  computed: {
    halfWidth: {
      get: function() {
        return this.width / 2;
      },
      set: function(val) {
        this.width = val * 2;
      }
    },
    halfHeight: function() {
      return this.height / 2;
    },
    halfPoint: function() {
      return {
        x: this.halfWidth,
        y: this.halfHeight
      };
    },
    myOkaneMatched: function() {
      return this.myOkaneList.filter(function(el) {
        return el.price <= this.okane;
      }, this);
    },
    myOkaneLimited: function() {
      return this.myOkaneMatchedSorted.slice(0, this.myOkaneLimit);
    },
    myOkaneMatchedSorted: function() {
      return this.myOkaneMatched.slice(0).sort((item1, item2) => {
        let ordering = item1.price > item2.price ? -1 : 1;
        return ordering * (this.myOkaneListOrder ? -1 : 1);
      });
    },
  },

// フィルター、結果のフィルターを通せる
  filters: {
    localeNum: function(val) {
      return val.toLocaleString();
    }
  },
// 変化を監視して処理する。
  watch: {
    'watchedData': {
       handler: function(newVal, oldVal) {
        if (newVal.age>40) {
          this.displayWatchedData = true;
        } else {
          this.displayWatchedData = false;
        }
      },
      deep: true,
      immediate: true
    }
  },
  // 独自ディレクティブ 例えばv-focusとして使われる。
  directives: {
    // 要素が挿入されたときにフォーカスする。
    focus: {
      inserted: function(el) {
        el.focus();
      }
    }
  }
});
</script>