问题描述:
项目中遇到一个场景:需要动态的改变vuex中state中的某属性值。但是在修改时遇到报错"xx" was assigned to but it has no setter。
思考:
出现这个错误的原因可能是我在页面中直接修改了state属性,而不是通过mutation来修改。在vuex中,state属性只能通过mutation来修改,以确保单项数据流的正确性。
使用计算属性实现VUEX双向绑定
例:属性selectedMethod实现双向绑定
// Vuex store中
const store = new Vuex.Store({
state: {
selectedMethod: ''
},
mutations: {
updateSelectedMethod(state, newValue) {
state.selectedMethod = newValue;
}
},
//一定要用getters
getters: {
selectedMethod: state => state.selectedMethod
}
});
//页面
<template>
<div>
<label>Select a method:</label>
<select v-model="selectedMethod">
<option value="method1">Method 1</option>
<option value="method2">Method 2</option>
<option value="method3">Method 3</option>
</select>
</div>
</template>
<script>
import { mapGetters, mapMutations } from 'vuex';
export default {
computed: {
...mapGetters(['selectedMethod']),
//使用get,set
selectedMethod: {
get() {
return this.$store.getters.selectedMethod;
},
set(newValue) {
this.$store.commit('updateSelectedMethod', newValue);
}
}
}
}
</script>