Nuxt.jsでVuexを使う方法
Nuxt.jsでVuexを使う方法を紹介します。
目次から読む
Nuxt.jsでVuexを使う方法
Nuxt.jsでは、Vuexをnpmなどでdependenciesにインストールする必要はありません。Classic ModeとModules Mode
Nuxt.jsのVuexを利用する場合次の2つのモードがあります。- Classic Mode
- Modules Mode
store/index.jsを作成
storeフォルダが作成されているので、そこにindex.jsを作成します。 storeフォルダがない場合は、自分で作成します。import Vuex from 'vuex'
const createStore = () => {
return new Vuex.Store({
state: {},
mutations: {},
actions: {},
getters: {}
})
}
export default createStore
そして、上のようにVuexをインポートします。
そして、Nuxtからコールできるように、オブジェクトではなく、関数を作成します。
それぞれのユーザーに個別のVuex Storeを返せるように、returnでVuexのStoreを返します。
そして、最後にエクスポートします。
使い方は、普通のVuexと同じです。
store/index.jsの具体例
import Vuex from 'vuex'
const createStore = () => {
return new Vuex.Store({
state: {
loadedProducts: []
},
mutations: {
setProducts(state, products) {
state.loadedProducts = products
}
},
actions: {
setProducts(vuexContext, products) {
vuexContext.commit('setProducts', products)
}
},
getters: {
loadedProducts(state) {
return state.loadedProducts
}
}
})
}
export default createStoreVuexを使う
pagesのvueファイルのscriptで、次のように使用します。 created() {
this.$store.dispatch('setProducts', this.loadedProducts)
}