<!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>
 (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)

运行后,在用户名输入,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.改正后,在组件内部再构建一套属性域,从而与外界解耦

05-16 20:32