为什么在nuxtServerInit提交后我的Vuex状态没有改变?

时间:2018-07-21 07:23:02

标签: javascript vue.js vuex nuxt.js contentful

我一直在使用nuxtServerInit从连续型CMS中获取数据,并提交了将数据添加到类别状态对象的更改。但是,即使我尝试在组件上呈现类别,类别也始终显示为空。

我可以console.log在变异函数中查看数据,为什么不将其推送到类别状态?

import Vuex from 'vuex'
import {createClient} from '~/plugins/contentful.js' //contentful plugin function

const client = createClient()
const createStore = () => {
  return new Vuex.Store({
    state: {
      categories: {}
    },
    mutations: {
      addCategories(state, data) {
        state.categories += data.items
      }
    },
    actions: {
      async nuxtServerInit(context) {
        client.getEntries({
            content_type: 'category' //fetch everything with the content type set to category
          })
          .then(response => context.commit('addCategories', response))
          .catch(console.error)
      }
    },
  })
}

export default createStore

1 个答案:

答案 0 :(得分:0)

import Vue from 'vue'
import Vuex from 'vuex'

import { createClient } from '~/plugins/contentful'

const client = createClient()

export default = () => new Vuex.Store({
  state: {
    categories: {}
  },

  mutations: {
    addCategories (state, data) {
      Vue.$set(state, 'categories', [...data.items, ...state.catagories])
    },
  },

  actions: {
    async nuxtServerInit ({ commit }) {    
      let response

      try {
        response = await client.getEntries({ content_type: 'category' })
      }
      catch (error) {
        console.log(error)
      }

      context.commit('addCategories', response)
    },
})