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: '<section class="login">' +
			'<div class="form-group"><label>用户名</label><input id="txtUser" v-model="uName"/></div>' +
			'<div class="form-group"><label>密码</label><input id="txtPwd" type="password" v-model="uPwd"/></div>' +
			'<div class="form-group"><input type="submit" value="提交" v-bind:disabled="btndisable"/></div></section>',
		computed:{
			btndisable:function(){
				return (this.uName||'').length>0&&(this.uPwd||'').length>0?false:true;
			}
		}
	});
	new Vue({
		el: '#form'
	})
})(window)
html代码:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>vue Learn</title>
		<script src="https://unpkg.com/vue/dist/vue.js"></script>
		
	</head>
	<body>
		<form id="form" method="post">
			<login></login>
		</form>
		<script src="./js/vue/v1.js"></script>
	</body>
</html>
运行后,在用户名输入,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: '<section class="login">' +
			'<div class="form-group"><label>用户名</label><input id="txtUser" v-model="name"/></div>' +
			'<div class="form-group"><label>密码</label><input id="txtPwd" type="password" v-model="pwd"/></div>' +
			'<div class="form-group"><input type="submit" value="提交" v-bind:disabled="btndisable"/></div></section>',
		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.改正后,在组件内部再构建一套属性域,从而与外界解耦




评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值