nishimura.clubnishimura.club

Nuxt.jsでStoreを分割する方法

作成日
2021-02-13
更新日
2021-02-13

はじめに

基本的な所作は、NuxtJS ストアに書いてあります。 nuxtServerInitindex.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に記載しても、pagescomponentsで取得できなかったので、(詳しく調べてはいない)

this.$store.state.post.posts

上記のように、stateから値を取得している。

Related

Tags

NuxtJS

Share