【问题标题】:Vuex reference not returning correct valueVuex 参考没有返回正确的值
【发布时间】:2020-04-08 18:18:20
【问题描述】:

我在这样的对象中引用 VueX getter:

computed : {
    ...mapGetters(['activeLayer']),
}

商店吸气剂看起来像这样:

getters : {
    activeLayer : state => state.views[state.activeView].layers[state.views[state.activeView].activeLayer]
}

然后我使用手表来监控变化:

created {
    var that = this;
    this.$store.watch( function(state) {return state.views[state.activeView].activeLayer}, 

        function() {
            console.log(that.activeLayer); // Returns initial value
            that.$store.state.views[this.$store.state.activeView].layers[this.$store.state.views[this.$store.state.activeView].activeLayer]; // Returns correct value
        }

    ,{ deep: true } )
}

问题是当存储更改时activeLayer 不会更新为新值。

如何强制activeLayer 更新?

【问题讨论】:

  • 更改activeLayer的代码是什么? Getter 本质上是被动的,不需要强制更新。
  • @Dan 我的想法也是如此,但是当我通过 this.$store.state 等直接引用活动层时。我得到与使用 mapGetters 映射的 activeState 不同的结果。

标签: vue.js vuex


【解决方案1】:

尝试改用mapState,观察变化会是这样的:

import { mapState } from 'vuex';
computed: { ...mapState(['activeLayer']), }
watch: {
     activeLayer(newValue, oldValue) {
          console.log(newValue);
     }
},

【讨论】:

  • 这不是带走了使用吸气剂的意义吗?我想缩短极长的状态变量并在多个组件中使用它。
  • 由于您希望它在商店更改时自动更新,而不是仅在开始时获取,mapState 是要走的路。您不需要设置吸气剂。您可以在任何地方使用此方法。
  • 有道理,但我如何将变量缩短为 activeLayer 并保持其反应性?
  • 如果您使用mapState,您可以将其引用为this.activeLayer,它会在更新时正常更改。
  • 但是 activeLayer “不是”顶级或真实属性,它是一个动态对象。
猜你喜欢
  • 1970-01-01
  • 2014-11-26
  • 2019-03-21
  • 1970-01-01
  • 2014-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多