【问题标题】:Dynamically populate Vuex state动态填充 Vuex 状态
【发布时间】:2018-05-17 13:07:13
【问题描述】:

我需要根据根组件中的data 变量加载不同版本的状态。

App.vue:

export default {
  store : store,
  name: 'app',
  data() {
    clientId : 1  
  }
}

store.js:

export const store = new Vuex.Store({
  state : {
    clientConfig : clientConfig
});

clientConfig 将存储在单独的文件中。

根据对初始 Vuejs 应用程序的一些输入,实现 Vuex 状态的动态/编程加载的最佳方法是什么?

谢谢!

【问题讨论】:

  • 一种解决方案是将所有clientConfig加载到您的商店,并使用getters获取与clientId对应的配置
  • 是的,但是整个应用程序将充满if client = x {get.config.a} 对还是我错过了什么?
  • 您也可以将clientId 存储在vuex 中。然后从vuex store 读取数据
  • 一个小例子会很棒:)

标签: javascript vue.js vuejs2 vuex


【解决方案1】:

这是一种可能的解决方案:

export const store = new Vuex.Store({
  state : {
    clientConfigs :{
      "1": clientConfig1,
      "2": clientConfig2
    },
    clientId: "1"
  },
  getters: {
    currentClientConfig: state => {
      return state.clientConfigs[state.clientId]
    }
  },
  mutations: {
   setClientId (state, newValue) {
     state.clientId = newValue
   }
  }
});

在您的组件中,您可以通过this.$store.getters.currentClientConfig 访问配置

要更新clientId,您可以使用突变。在组件中,您可以使用 this.$store.commit('setClientId', yourNewClientId)

【讨论】:

  • 这看起来不错 - 但我如何设置clientId : 1,现在我正在测试一个在组件上使用 Vue.set() 的解决方案。
  • 我更新了我的答案,你可以通过mutations更新clientId。欲了解更多信息vuex.vuejs.org/en/mutations.html
  • 非常感谢!只有一件事,由于加载/渲染的顺序而引发错误 - 因为模板在定义之前调用currentClientConfig - 应用程序可以工作,但错误消息很糟糕:(
猜你喜欢
  • 2019-11-27
  • 1970-01-01
  • 2019-08-17
  • 2019-07-15
  • 1970-01-01
  • 1970-01-01
  • 2019-07-22
  • 2021-09-23
  • 2018-01-17
相关资源
最近更新 更多