Nuxt.jsでStoreを分割する方法
はじめに
基本的な所作は、NuxtJS ストアに書いてあります。
nuxtServerInitがindex.js
のみ使用できることに注意です。
サンプルコード
例
- Apollo Clientを使用している
- SSRでPostモデルのデータを取得する
.
├── index.js
└── post.js
index.js
async nuxtServerInit({ commit }, { req }) {
const response = await this.app.apolloProvider.defaultClient.query({
query: fetchPosts,
})
commit("user/setPosts", response.data.posts)
},
post.js
export const state = () => ({
posts: [],
})
export const getters = {}
export const actions = {}
export const mutations = {
setPosts(state, posts) {
state.posts = posts
},
}
getters
に記載しても、pages
やcomponents
で取得できなかったので、(詳しく調べてはいない)
this.$store.state.post.posts
上記のように、state
から値を取得している。