有时候我们需要使用v-model实现对vuex的state中数据的双向绑定,我们该如何实现呢?
我们的html
代码如下:
<div id="app"> 用户名:<input type="text" v-model="username" /> </div>
计算属性为:
// ... computed:{ username:{ get(){ return this.$store.state.username; } set(value){ this.$store.commit('updateUsername',value); } } }
vuex中的代码为:
const store = new Vuex.Store({ // ... state:{ username:"小明" }, mutations:{ updateUsername(state,playload){ state.username = playload; } }, //严格模式 //strict:true })
注意事项:
严格模式下,无论何时发生了状态变更且不是由
严格模式下,无论何时发生了状态变更且不是由
mutation
函数引起的,将会抛出错误。因此使用v-model
后不要使用严格模式,而且不要在生产环境下启用严格模式!