zoukankan      html  css  js  c++  java
  • 解决在V2.0中子组件使用v-model接收来自父组件的值异常

    当我们使用父组件向子组件传值,当子组件中是v-model使用该值时会报:[Vue warn]: Avoid mutating a prop directly since the value will be overwritten

    原因为:在Vue 2.x中移除了组件的props的双向绑定功能,如果需要双向绑定需要自己来实现。

    解决办法为:创建针对props属性的watch来同步组件外对props的修改(单向)

    在组件外(父组件)修改了组件的props,会同步到组件内对应的props上,再创建一个针对props属性result的watch(监听),当props修改后对应data中的副本myResult也要同步数据。代码实例如下:

    <template>
    <div>
      <input v-model="myResult" placeholder="v-model里面的值来自外部"/>
    </div>
    </template>
    
    <script type="text/ecmascript-6">
      export default {
        data() {
          return {
            myResult: this.result
          }
        },
        props: ["result"],
        watch: {
          result(val) {
            this.myResult = val;//新增result的watch,监听变更并同步到myResult上
          }
        },
      }
    </script>
    
    <style>
    
    </style>

    最终异常消除。

    文章参考了此链接

     

  • 相关阅读:
    sql语句相关操作
    点菜系统数据库课程设计
    JDBC连接mysql编程
    JFrame画图基础和事件监听
    JFrame编程
    Java基础知识
    bzoj1047-理想的正方形(二维单调队列)
    Project Eular 233/ BZOJ 1041
    Open Train 10352
    Codeforces Round 492 (Div.1)
  • 原文地址:https://www.cnblogs.com/wfaceboss/p/10499474.html
Copyright © 2011-2022 走看看