vue.js - 无法访问 Vuex 存储对象的属性

标签 vue.js vue-component nuxt.js vuex vuex-modules

我使用名为 config.json 的 JSON 文件初始化我的商店:

{
  "branding": {
    "button": {
      "secondary": {
        "background_color": "#EC6B24",
        ...
      },
      ...
    }
  }
}

...我在商店中导入的:

import templateConfig from '@/config.json'

export const state = () => ({
  branding: {}
})

export const mutations = {
  setConfig (state, data) {
    state.branding = templateConfig.branding
  }
}

export const actions = {
  initializeStore ({ state, commit }, data) {
    commit('setConfig', data)
  }
}

现在,在 View 的 mounted Hook 中,我调用存储操作 (this.initializeStore()),以便在页面加载时填充存储。

问题是,当我在 View 的子组件之一中尝试访问嵌套属性时,如下所示:

computed: {
  ...mapState({
    bgColor: state => state.template.branding.button.secondary.background_color
  })
}

...我收到此错误:

Cannot read property 'secondary' of undefined

为什么?

编辑:下面是父 View 组件的代码。

import { mapActions } from 'vuex'

export default {
  mounted () {
    this.initializeStore()
  },
  methods: {
    ...mapActions({
      initializeStore: 'initializeStore'
    })
  }
}

最佳答案

该错误意味着状态当时只有初始值,并且尚未调用该操作(在子级映射状态后装载父级)。您可以尝试在父级的 created Hook 中执行该操作。

但是,如果 initializeStore 在初始化时仅调用一次,您可以完全删除该操作(和突变),并直接从导入的 json 中定义您的 state :

import templateConfig from '@/config.json'

export const state = () => ({
  branding: templateConfig.branding
})

无论如何, Action /突变永远不会使用有效负载。

如果数据是获取而不是导入,我建议查看 nuxtServerInit和/或 fetch/asyncData Hook 。

关于vue.js - 无法访问 Vuex 存储对象的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66528824/

相关文章:

javascript - 将 setTimeout 函数分配给 Vue 方法

vue.js - 将属性默认值注入(inject)第 3 方 Vue 组件

vue.js - 功能组件内的 Vue 导入组件

javascript - nuxt 从哪里导入全局模块node_modules

css - 如何覆盖填充 : 0; from sass?

javascript - TypeScript 无法检测 *.vue 文件

Vue.js 使用 prop 值作为类名

vue.js - Composition api使用这个

javascript - $store 属性在使用计算属性(Vuex)时不是 react 性的

vue.js - 我该如何解决 "Interpolation inside attributes has been removed. Use v-bind or the colon shorthand"? Vue.js 2