Vue avoid mutating a prop directly since the value will be overwritten

学习Vue,从官方文档开始。看了半天不过瘾,决定实现一个登陆组件。开始代码如下:

js代码(v1.js)

(function(w) {
	Vue.component('login', {
		props: ['uName', 'uPwd'],
		template: '',
		computed:{
			btndisable:function(){
				return (this.uName||'').length>0&&(this.uPwd||'').length>0?false:true;
			}
		}
	});
	new Vue({
		el: '#form'
	})
})(window)
html代码:



	
		
		vue Learn
		
		
	
	
		
运行后,在用户名输入,console界面中弹出警告:

Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "uName" 。


改为:

(function(w) {
	Vue.component('login', {
		props: ['uName', 'uPwd'],
		template: '',
		data:function(){
			return {
				name:"",
				pwd:""
			}
		},
		computed:{
			btndisable:function(){
				return (this.name||'').length>0&&(this.pwd||'').length>0?false:true;
			}
		}
	});
	new Vue({
		el: '#form'
	})
})(window)

运行OK,没有警告。


总结:

1.v-model 默认是双向绑定,开始时使用默认 属性uName 双向绑定,意味着存在,组件内部 修改uName,从而影响外部 组件的风险。

2.改正后,在组件内部再构建一套属性域,从而与外界解耦




你可能感兴趣的:(Js)