我的input框v-model绑定的是Vuex里的state,但是没有做到双向绑定。今天就聊一下如何优雅的绑定Vuex
- 第一种
<div>
<input type="text" v-model="$store.state.Root.value" />
<p>{{ $store.state.Root.value }}</p>
// 这里为什么是state.Root.value 是我这里用到了vuex里的modules
// 关于modules我会用新一篇文章来介绍,这里大家看看就行
</div>
//我们都知道v-model是一种语法糖:
<input type="text" v-model="val" />
等价于
<input type="text" :value="value" @input="value = $event.tagret.value" />
其实第一种方法就是利用了v-model的语法糖,至于为什么不需要mutations我猜是因为对象的引用关系
- 第二种(优雅型,通过computed)这种方式一直是我在团队里比较建议使用的,因为它遵从了Vuex的核心理念:使用mutations来改变state
<input v-model="modelData" />
computed: {
modelData: {
get() {
// 这里也是用了Vuex里的 modules 大家可以当成普通的变量来看
return this.$store.state.modelData
},
set(newVal) {
this.$store.commit('modelData', newVal)
}
}
}
注: computed其实可以接受两个参数:
get:当获取值时会触发
set:当修改值时会触发并有新值作为参数返回
- 所以我在get里获取Vuex
- 在set里调用 mutations
// store.js
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
modelData:' '
}
},
getters: {},
mutations: {
modelData(state, payload) {
state.value = payload
}
}
actions: {}
});
export default store;
window.store = store;