【问题标题】:Can't access my store object from my component无法从我的组件访问我的商店对象
【发布时间】:2021-06-05 15:36:46
【问题描述】:

在我的商店模块 /store/template.js 我有:

const templateConfig = {
  branding: {
    button: {
      secondary: {
        background_color: '#603314',
        background_image: ''
      }
    }
  }
}

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

export const actions = {
  initializeStore (state) {
    state.branding = templateConfig.branding
  }
}

initializeStore() 在应用初始加载时被调用)

我想在我的组件中检索branding 对象的品牌:

computed: {
  ...mapState({
    branding: state => state.template.branding
  })
}

但是当我尝试console.log() branding 时,我看到了这个:

为什么我不直接看到branding 对象? (这到底是什么?)

【问题讨论】:

标签: javascript vue.js nuxt.js vuex vuex-modules


【解决方案1】:

你需要import { mapState, mapActions } from 'vuex'(我猜已经完成了)。

然后,你可以写这个

...mapState(['branding']) // or ...mapState('@namespacedModule', ['branding'])

不过,您为什么不直接输入状态(使用您的 background_color)而不是通过 Vuex 操作?

如果你想保持这种状态,在尝试访问状态之前不要忘记在你的组件中await this.initializeStore()

【讨论】:

  • 如果我这样做 ...mapState(['branding']) 我会得到undefined,如果我这样做 ...mapState('@namespacedModule', ['branding']) 我会得到我提到的同样奇怪的事情!
  • 他看到 observable 的事实意味着映射已经在工作
【解决方案2】:

您需要始终使用突变来更改状态。您可以从您的操作中调用一个:

export const mutations = {
  SET_BRANDING(state, payload) {
    state.branding = payload;
  }
}
export const actions = {
  initializeStore ({ commit }) {
    commit('SET_BRANDING', templateConfig.branding);
  }
}

观察者看到的情况是正常的,表明branding对象已经成功映射和访问。

你看到的是 Vue 的 observable 对象,这是 Vue 实现反应性的方式。没有这个,就没有反应性,你会在所有顶级反应性对象上看到这样的包装器。你可以假装它不存在。

Vue 实际上在内部将相同的“包装器”应用于data 对象以使其可观察:

在内部,Vue 在 data 函数返回的对象上使用 this。

您不会在其他响应式属性上看到它,但如果它们是响应式的,则它们属于某个父可观察对象。


【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-11
    • 1970-01-01
    • 2020-02-05
    • 1970-01-01
    • 2016-04-06
    • 2019-08-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多