【问题标题】:How to keep vue computed property the same as vuex state and vice versa?如何保持 vue 计算属性与 vuex 状态相同,反之亦然?
【发布时间】:2019-06-22 08:12:03
【问题描述】:

我想保持 vue 计算属性与 vuex 状态相同,反之亦然。但它没有达到我的预期结果。这是一个简单的小提琴来展示我的问题。 https://jsfiddle.net/qtttttttttting/Lteoxz9f/22/

const store = new Vuex.Store({
  state: {
    fullName: "hhh hhh"
  },
  mutations: {
    change (state,data) {
      state.fullName = data;
    }
  }
})
new Vue({
  el: "#app",
  data(){return {}},
  methods: {
    toggle: function(){
            console.log(333)
            this.fullName="qqq ttt";
            console.log(this.fullName)
    }
  },
    computed: {
        fullName: {
            // getter
            get: function () {
                console.log(111);
                return store.state.fullName;
            },
            // setter
            set: function (newValue) {
                console.log(222);
                store.commit("change", this.fullName);
            }
        }
    },
    watch:{
        fullName(){
            console.log(444);
            store.commit("change", this.fullName);
        }
    }
})

【问题讨论】:

  • 如果您的小提琴不能准确地代表您的生产环境,请发布生产代码(参考@gleam 的答案的评论)。

标签: vue.js vuex


【解决方案1】:

您的计算设置器中有错字: https://jsfiddle.net/0o2cnrvf/

        set: function (newValue) {
            console.log(222);
            store.commit("change", newValue);
        }

【讨论】:

  • 谢谢你。我写了一封信。但是在我的项目中,在生产环境中,代码是不行的。
  • 尝试删除不必要的观察者
猜你喜欢
  • 2017-02-26
  • 2017-12-31
  • 2012-06-09
  • 2019-10-19
  • 2020-01-10
  • 2021-05-08
  • 2019-02-11
  • 2018-05-19
  • 2019-04-23
相关资源
最近更新 更多