<!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>
1 (function(w) { 2 Vue.component('login', { 3 props: ['uName', 'uPwd'], 4 template: '<section class="login">' + 5 '<div class="form-group"><label>用戶名</label><input id="txtUser" v-model="uName"/></div>' + 6 '<div class="form-group"><label>密碼</label><input id="txtPwd" type="password" v-model="uPwd"/></div>' + 7 '<div class="form-group"><input type="submit" value="提交" v-bind:disabled="btndisable"/></div></section>', 8 computed:{ 9 btndisable:function(){ 10 return (this.uName||'').length>0&&(this.uPwd||'').length>0?false:true; 11 } 12 } 13 }); 14 new Vue({ 15 el: '#form' 16 }) 17 })(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" 。
修改之后:
1 (function(w) { 2 Vue.component('login', { 3 props: ['uName', 'uPwd'], 4 template: '<section class="login">' + 5 '<div class="form-group"><label>用戶名</label><input id="txtUser" v-model="name"/></div>' + 6 '<div class="form-group"><label>密碼</label><input id="txtPwd" type="password" v-model="pwd"/></div>' + 7 '<div class="form-group"><input type="submit" value="提交" v-bind:disabled="btndisable"/></div></section>', 8 data:function(){ 9 return { 10 name:"", 11 pwd:"" 12 } 13 }, 14 computed:{ 15 btndisable:function(){ 16 return (this.name||'').length>0&&(this.pwd||'').length>0?false:true; 17 } 18 } 19 }); 20 new Vue({ 21 el: '#form' 22 }) 23 })(window)
運行OK,沒有警告。
總結:
1.v-model 默認是雙向綁定,開始時使用默認 屬性uName 雙向綁定,意味着存在,組件內部 修改uName,從而影響外部 組件的風險。
2.改正后,在組件內部再構建一套屬性域,從而與外界解耦
