首页 > 解决方案 > 如何保持 vue 计算属性与 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);
        }
    }
})

标签: vue.jsvuex

解决方案


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

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

推荐阅读