Nuxt.jsのstoreディレクトリを簡単に使ってみます。
今回はNuxt 2を使用しています。
サンプルコード
storeディレクトリにindex.jsを追加して、ストアを有効化します。
export const state = () => ({
counter: 0
})
export const mutations = {
increment(state) {
state.counter++
}
}
pages/index.vueで実際に使ってみます。
<template>
<div>
<div>{{ counter }}</div>
<button @click="increment">+</button>
</div>
</template>
ステートの表示とボタンクリックでステートの更新を行う想定です。
JavaScriptは以下のようになります。
export default {
computed: {
counter() {
return this.$store.state.counter
}
},
methods: {
increment() {
this.$store.commit('increment')
}
}
}
this.$store.state.counterでステートの表示、this.$store.commitでステートの更新になります。
次にstoreディレクトリ内にdemoディレクトリを作成して、その中にtest.jsを追加します。
export const state = () => ({
message: 'Hello'
})
先ほどのデモに表示を追加してみます。
<div>
<div>{{ counter }}</div>
<button @click="increment">+</button>
<div>{{ msg }}</div>
</div>
JavaScriptでmessageの呼び出しを追加します。
export default {
computed: {
counter() {
return this.$store.state.counter
},
msg() {
return this.$store.state.demo.test.message
}
},
methods: {
increment() {
this.$store.commit('increment')
}
}
}
store/demo/test.jsのステートのmessageを呼び出す場合、this.$store.state.demo.test.messageのようになります。
コメントが承認されるまで時間がかかります。