自定义v-model报错: Avoid mutating a p

2021-05-17  本文已影响0人  码农梦醒

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

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

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

<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>
上一篇 下一篇

猜你喜欢

热点阅读