Vue.js / Nuxt.js / Vuexの書き方のメモ

すぐに忘れてしまうのでテンプレートを残しておきます。

Vue.js / Nuxt.js

import Element from "~/components/element.vue";

export default {
  components: {
    "element": Element,
  },
  data() { return {
    field1: value1,
    field3: value3,
  } },
  computed: {
    field2() {
      return value2;
    },
    field3: {
      get() {
        return this.field3Impl;
      },
      set(newVal) {
        this.field3Impl = newVal;
      },
    },
  },
  methods: {
    method1() {
      // なにか
    },
  },
  created() {
    // なにか
  },
  beforeRouteUpdate(to, from, next) {
    // to.path が新しいURLのパス部分
    next(); // 最後に呼ぶ
  },
  mounted() {
    // なにか
  },
  beforeDestroy() {
    // なにか
  },
}

Vuex

  • state
    • 値の集まり、ステータス
  • mutations
    • ステータスの操作
    • 定義の例: increment(state, n)
    • 呼び出しの例: context.commit("increment", 10)
  • actions
    • 非同期処理を含む任意の処理
    • 定義の例: increment (context, n)
    • 呼び出しの例: context.dispatch("increment", n)

Vue.js

const store = new Vuex.Store({
    state: {
        count: 0,
    },
    mutations: {
        increment(state, n) {
            // なにか
            state.count += n;
        },
    },
    actions: {
        increment(context, n) {
            // なにか
            context.commit("increment", n);
        },
    },
}

Nuxt.js

export const state = () => ({
    count: 0,
});
export const mutations = {
    increment(state, n) {
        // なにか
        state.count += n;
    },
};
export const actions = {
    increment(context, n) {
        // なにか
        context.commit("increment", n);
    },
};