工作的时候有好多人问到了一个问题:
我的input框v-model绑定的是Vuex里的state,但是没有做到双向绑定。今天就聊一下如何优雅的绑定Vuex
- 第一种(暴力流)
v-model直接连接store
<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="getVal" />
computed: {
getVal: {
get() {
// 这里也是用了Vuex里的 modules 大家可以当成普通的变量来看
return this.$store.state.Root.value
},
set(newVal) {
this.$store.commit('handleVal', newVal)
}
}
}
computed其实可以接受两个参数:
get:当获取值时会触发
set:当修改值时会触发并有新值作为参数返回
- 所以我在get里获取Vuex
- 在set里调用 mutations
// store.js
mutations: {
handleVal(state, payload) {
state.value = payload
}
}
转载自
作者:我是居居
链接:https://juejin.im/post/5c2319f3e51d45745544f270
来源:掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。