出现这种情况的原因是我们直接改变子组件的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>

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐