出现Avoid mutating a prop directly since the value will错误 已解决

出现这种情况的原因是我们直接改变子组件的props值,众所周知,props是父向子传值的一种形式。当我们子组件的props值要改变的时候,不能直接通过改变子组件的props来改变父组件。

例如:
父组件

<template>
  <div id="app">
    <son v-model="count" />
  </div>
</template>

<script>
import son from "./components/son"
export default {
  name: "App",
  components: {
    son
  },
  data() {
    return {
      count:150
    };
  },
  
};
</script>

子组件:

<template>
  <div>
      <input type="text" v-model.number="value">
      <button @click="handleClick">按钮</button>
  </div>
</template>

<script>
export default {
name:"son",
props: {
   value:{
       type:Number
   }
},
methods:{
    handleClick(){
        this.$emit('input',100)
    }
}
}
</script>

<style>

</style>

当我们直接在输入框里边修改时,会触发input的v-model,也就是会反向改变props,会出先一下错误: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: "value"found in…

解决方式

  • 使用computed方式
<template>
  <div>
    <input type="text" v-model.number="count" />
    <button @click="handleClick">按钮</button>
  </div>
</template>

<script>
export default {
  name: "son",
  props: {
    value: {
      type: Number,
    },
  },
  computed: {
    count: {
      get() {
        return this.value;
      },
      set(newValue) {
        this.$emit("input", newValue);
      },
    },
  },
  methods: {
    handleClick() {
      this.$emit("input", 100);
    },
  },
};
</script>
  • data加watch
<template>
  <div>
    <input type="text" v-model.number="count" />
    <button @click="handleClick">按钮</button>
  </div>
</template>

<script>
export default {
  name: "son",
  watch:{
      count:{
          handler(newValue){
                this.$emit('input',newValue)
          }
      }
  },
  props: {
    value: {
      type: Number,
    },
  },
  data(){
      return {
          count:this.value
      }
  },
  methods:{
      handleClick(){
          this.$emit('input',100)
      }
  }
};
</script>

<style></style>

  • 5
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值