有没有办法将 vue 数据值与全局存储状态值同步?
is there a way to sync vue data values with global store state values?
我想用 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);
},
}
您不能以这种方式在 data
选项中引用数据 属性 (storeState
),而且您也不需要它。您应该使用计算来将组件值与 Vuex 值同步。删除两个数据值:
computed: {
Counter() {
return this.$store.state.Counter;
}
}
或使用mapState
:
import { mapState } from 'vuex'
computed: {
Counter() {
...mapState(['Counter'])
}
}
还要确保您的商店变更在 mutations
内并使用正确的语法:
state: {
Counter: 1
},
mutations: {
CounterUpdater(state, value) {
state.Counter = value;
}
}
还建议根据 camelCase 约定命名变量(即在代码中表示小写 counter
)
我想用 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);
},
}
您不能以这种方式在 data
选项中引用数据 属性 (storeState
),而且您也不需要它。您应该使用计算来将组件值与 Vuex 值同步。删除两个数据值:
computed: {
Counter() {
return this.$store.state.Counter;
}
}
或使用mapState
:
import { mapState } from 'vuex'
computed: {
Counter() {
...mapState(['Counter'])
}
}
还要确保您的商店变更在 mutations
内并使用正确的语法:
state: {
Counter: 1
},
mutations: {
CounterUpdater(state, value) {
state.Counter = value;
}
}
还建议根据 camelCase 约定命名变量(即在代码中表示小写 counter
)