【问题标题】:Vue + Vuex reactivity of dictionary object字典对象的Vue + Vuex反应性
【发布时间】:2018-11-29 14:32:16
【问题描述】:

我正在使用 Vue + Vuex 来管理状态。

让我们有商店:

state: {
  nodes: {}
},
actions: {
  loadNodes ({ commit }, parameter) {
     axios.get('http://URL' + '/nodes', {
        params: {
          name: parameter['name'],
          type: parameter['type']
        }
      }).then((response) => {
        commit('nodeActivity', { uid: parameter['uid'], res: response.data })
    })
  }
},
mutations: {
  nodeActivity (state, data: {uid, res}) {
    Vue.set(state.nodes, data.uid, data.res)
  }
},
getters: {
  getNodes: state => state.nodes
}

这可能没问题,在nodes 中有一个字典结构{ id: data }

现在我有了带钩子的组件:

created () {
    this.$store.dispatch('nodeActivity', { uid: this.$props.uid, name: this.$props.namepar, type: this.$props.typepar })
  } 

所以 API 调用得到了一些数据并异步存储。有用。但是我需要得到具体的uid 类似this.$store.getters.getNodes[0] 的东西,它不起作用但this.$store.getters.getNodes 可以正常工作,所以我认为由于Vue.set(..),反应性是好的。即使我使用const tmp = this.$store.getters.getNodestmp 包含整个字典)然后使用tmp2 = tmp[0],tmp2 也没有反应。 我不知道为什么。 我从 Vue 开始,所以我很欣赏如何更改商店设计的提示。

【问题讨论】:

  • 我总是使用指向存储中的 getter 或键的计算属性。你试过了吗?
  • 不,因为我需要应用程序索引页面上的图表数据。它必须在create() 时加载要存储的数据并立即使用该数据(在mount() 中)来创建图表。

标签: javascript rest vue.js vuex


【解决方案1】:

嗯,我找到了一个很差而且可能超出设计的解决方案。 我只有watcher 用于从存储加载数据的变量,例如const tmp = this.$store.getters.getNodes。当tmp 发生变化时,我可以通知它并分配变量tmp2 = tmp[number],因此行为是被动的。我觉得这个解决方案很hacky。

【讨论】:

    猜你喜欢
    • 2021-08-21
    • 2017-11-02
    • 2020-10-23
    • 1970-01-01
    • 1970-01-01
    • 2021-07-08
    • 2019-09-08
    • 2018-10-01
    • 2021-10-04
    相关资源
    最近更新 更多