Nuxt.jsでVuexをモジュールモードで利用する
モジュール(store)の用意
モジュールを用意します。コレがVuexのsotreとして利用されます。
/**
* store/counter.js
* このファイル名がcounter.jsなので、モジュール名はcounterになる。
*/
export const state = () => ({
count: 123
})
export const mutations = {
increment (state, v) {
state.count += v
}
}
利用方法
以下のファイルをpages/test.vue
として作成しました。
<template>
<section class="container">
<div>
<button @click='inc'>{{value}}</button>
</div>
</section>
</template>
<script>
const moduleName = 'counter' // store/counter.js
export default {
computed: {
value () {
return this.$store.state[moduleName].count
// 以下でも同じ
// return this.$store.state.counter.count
}
},
methods: {
inc: function () {
const mutationName = 'increment' // sotre/counter.jsの中に書いたmutationsの中にある関数名
this.$store.commit(`${moduleName}/${mutationName}`, 1)
// 以下でも同じ
// this.$store.commit(`counter/increment`, 1)
}
}
}
</script>
これで、/testにアクセスすれば、button上にCounterが表示され、それをクリックすれば値が増えることが確認できると思います。
公開日:2018/04/19