如何保持vue计算的属性与vuex状态相同,反之亦然?

时间:2019-01-29 08:47:40

标签: vue.js vuex

我想保持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);
        }
    }
})

1 个答案:

答案 0 :(得分:1)

您的计算设定者中有一个错字: https://jsfiddle.net/0o2cnrvf/

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