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


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

  • 相关阅读:
    js模板引擎-art-template常用总结
    安装 PLSQL笔记
    [转载]软件测试之Web测试经典总结
    网络相关概念笔记
    HTTP请求过程
    Postman newman
    Postman interceptor
    SoupUI学习资料
    Postman 基本操作学习
    Postman 安装 & 资料
  • 原文地址:https://www.cnblogs.com/xiaomili/p/6633997.html
Copyright © 2020-2023  润新知