Vuex 强调的是 Unidirection Dataflow, state 只能被读取,要写入 state 必须靠 mutation ,因此 v-model 无法直接写入 state 。
v-model 本质是 value property binding 与 input event 的 syntatic sugar,因此可以回归基本动作,使用 value 与 input 实现。
对store使用双向绑定会出现下面的情况
解决办法:
使用计算属性
//常见的计算属性
computed: {
example(){
return this.$store.state.text //只能返回值,
},
}
//完整的计算属性
computed: {
example: {
set(obj) { //先
this.$store.state.text = obj; //可以使用v-model传入的数据对store进行操作
}, get() { //后
return this.$store.text
}
},
}