问题阐述
我们都知道Vue
中 input
输入框的数据双向绑定是使用 v-model
实现的。但是如果绑定的数据是 Vuex- State
中的数据,直接使用v-model
会发生什么呢?
错误示范
store/index.js
state: {
inputVal: '默认值'
}
Component
<template>
<div class="home">
{{inputVal}}
<input type="text" v-model="inputVal">
</div>
</template>
computed: {
...mapState(['inputVal', ]),
},
当前我们去改inputVal 时,会报以下错误。
方案一
那么如何实现 vuex
的数据双向绑定呢?一共两种方案,我们先看方案一。方案一是利用v-model
的原理,value
绑定和input
事件实现数据双向绑定。
store/index.js
state: {
inputVal: '默认值',
},
//专门用来修改状态值的方法集合
//mutations内的函数不支持异步函数
mutations: {
changeData(state, v) {
state.inputVal = v
},
},
Component
<h2>方案一</h2>
{{inputVal}}
<input type="text" :value="inputVal" @input="updateMessage" name="" id="">
methods: {
updateMessage(e) {
this.$store.commit('changeData', e.target.value)
}
}
方案二
这种方式遵循的理念是使用
computed
其实可以接受两个参数:
get
:当获取值时会触发
set
:当修改值时会触发并有新值作为参数返回
store/index.js
state: {
message: "默认213值",
},
mutations: {
changeMessage(state, v) {
state.message = v;
}
},
Component
computed: {
message: {
get() {
return this.$store.state.message;
},
set(value) {
this.$store.commit('changeMessage', value)
}
}
},