3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Nuxt.js】Vuex クラシックモードとモジュールモードの書き方【コピペ用】

Posted at

#クラシックモード

store/index.js
import Vuex from "vuex"

const createStore = () => {
  return new Vuex.Store({
    state() {
      return {
        count: 0
      };
    },
    getters: {
      getCount: state => state.count
    },
    mutations: {
      incrementCountMutations(state) {
        state.count++;
      }
    },
    actions: {
      incrementCountActions({ commit }) {
        commit("incrementCountMutations");
      }
    }
  });
};

export default createStore

#モジュールモード

動作条件
・index.jsがstoreオブジェクトをexportしない
・store配下にindex.jsが存在しない

store配下にcounter.jsを作成

store/counter.js
export const state = () => ({
  count: 0
})

export const getters = {
  getCount: state => state.count
}

export const mutations = {
  incrementCountMutations(state) {
    state.count++;
  }
}

export const actions = {
  incrementCountActions({ commit }) {
    commit("incrementCountMutations");
  }
}

呼び出す(counter.jsの場合)

pages/index.vue
<template>
  <div>
    state : {{ $store.state.counter.count }}
    <br>
    getters : {{ $store.getters['counter/getCount'] }}
    <br>
    <button @click="$store.commit('counter/incrementCountMutations')">incrementCountMutations</button>
    <br>
    <button @click="$store.dispatch('counter/incrementCountActions')">incrementCountActions</button>
  </div>
</template>

#ヘルパー関数を使用する

pages/index.vue
<template>
  <div>
    state : {{ count }}
    <br>
    getters : {{ getCount }}
    <br>
    <button @click="incrementCountMutations">incrementCountMutations</button>
    <br>
    <button @click="incrementCountActions">incrementCountActions</button>
  </div>
</template>

<script>
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'
export default {
  computed: {
    ...mapState('counter', [
      'count'
    ]),
    ...mapGetters('counter', [
      'getCount'
    ])
  },
  methods: {
    ...mapMutations('counter', [
      'incrementCountMutations'
    ]),
    ...mapActions('counter', [
      'incrementCountActions'
    ])
  }
}
</script>
3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?