vue使用prop通信出错:Avoid mutating a prop directly since the value will be overwritten whenever the parent

在Vue.js中使用props进行父子组件通信时,出现错误提示:Avoid mutating a prop directly...。这是因为直接修改prop是不被允许的。解决方案包括使用$emit将数据变化通知父组件进行修改,或者将数据封装在对象中,子组件修改对象属性。通过这两种方式,可以避免直接修改prop导致的错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用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: “currentIndex”

产生错误的原因:在子组件中,你试图修改父组件通过props与子组件通信的数据。

两种解决方法

  1. 将这个父组件传进来的要修改的数据,通过$emit再传回给父组件,在父组件中进行修改。
  2. 当父组件通过props与子组件通信时,可以将数据放在一个对象中传递给子组件,这时再子组件就可以修改对象中的属性,也就修改了父组件传过来的数据。

例如(方法一):

父组件:

      <tab-control
        :titles="titles"
        @choseItem="choseItem"
        :currentIndex="currentIndex"
        ref="tabControl"
      ></tab-control>

	<script>
	date(){
		 currentIndex: 0 
		}
	methods:{
		choseItem: function(index) {
	      	this.currentIndex = index;//在父组件修改值
	    }
	 }
	</script>

子组件:

<template>
  <div class="tabControl">
    <ul>
      <li
        v-for="(item, index) in titles"
        :key="index"
        @click="choseItem(index)"
        :class="{ active: currentIndex === index }"
      >
        <span>{{ item }}</span>
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  name: "TabControl",
  props: {
    titles: {
      type: Array
    },
    currentIndex: {
      type: Number,
      default: 0
    }
  },

  methods: {
    choseItem: function(index) {
      //this.currentIndex = index;
      //注意:不能在子组件修改从父组件传过来的currentIndex,既然不能在这里修改,反正都要将index传出去,那就通过emit传出去吧
      //告知Home组件根据下标来给Goods传数据
      this.$emit("choseItem", index);
    }
  }
};
</script>

方法二:
在父组件传递一个对象,对象包含父子组件通信的数据

父组件:
<parent :objData="objData"></parent>
	data(){
	return {
		result:true
	}
}

子组件:
	props:{
		objData:{
			type:Object
	}
}


修改数据:
this.objData.result=false;

封装在对象中的通信数据修改也是不会报任何错误的。

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值