如何使用v-model实现双向绑定vuex的state

IT 文章6天前更新 小编
0 0 0

有时候我们需要使用v-model实现对vuex的state中数据的双向绑定,我们该如何实现呢?
我们的html代码如下:

用户名:

计算属性为:

// ...
computed:{
	  username:{
		  get(){
			  return this.$store.state.username;
		  }
		  set(value){
			  this.$store.commit('updateUsername',value);
		  }
	  }
  }

vuex中的代码为:

ad

程序员导航

优网导航旗下整合全网优质开发资源,一站式IT编程学习与工具大全网站

const store = new Vuex.Store({
	// ...
	state:{
		username:"小明"
	},
	mutations:{
		updateUsername(state,playload){
			state.username = playload;
		}
	},
	//严格模式
	//strict:true

})

[v_warn]注意事项:
严格模式下,无论何时发生了状态变更且不是由 mutation 函数引起的,将会抛出错误。因此使用v-model后不要使用严格模式,而且不要在生产环境下启用严格模式![/v_warn]

© 版权声明

相关文章

暂无评论

暂无评论...