【问题标题】:is there a way to sync vue data values with global store state values?有没有办法将 vue 数据值与全局存储状态值同步?
【发布时间】:2021-04-14 09:41:39
【问题描述】:

我想用 store.js 中的值更新我的数据值,这怎么可能?下面的代码给了我空白页错误。

App.vue

data() {
    return {
    storeState: store.state,
    Counter: this.storeState.Counter, 
    }
    }

store.js

   export const store = {
         state: {
         Counter: 1,
         }


     CounterUpdater(value) {
     this.state.Counter = (value);
     },
     }

【问题讨论】:

    标签: javascript vue.js vuejs2 vue-component vuex


    【解决方案1】:

    您不能以这种方式引用 data 选项内的数据属性 (storeState),而且您也不需要它。您应该使用计算来将组件值与 Vuex 值同步。删除两个数据值:

    computed: {
      Counter() {
        return this.$store.state.Counter;
      }
    }
    

    或者使用mapState:

    import { mapState } from 'vuex'
    
    computed: {
      Counter() {
        ...mapState(['Counter'])
      }
    }
    

    还要确保您的 store 突变位于 mutations 内并使用正确的语法:

    state: {
      Counter: 1
    },
    mutations: {
      CounterUpdater(state, value) {
         state.Counter = value;
      }
    }
    

    还建议根据camelCase 约定命名您的变量(即在您的代码中表示小写counter

    【讨论】:

    • 我不用vuex,我用的是simple global store,你能指导一下吗?
    • 为什么不使用 Vuex?
    • 听说是大中型项目,我只有几个变量
    • 这是不准确的,它适用于需要集中数据的任何规模的项目。
    猜你喜欢
    • 1970-01-01
    • 2020-02-23
    • 2020-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多