vue使用prop通信出错:Avoid mutating a prop directly since the value will be overwritten whenever the parent
报错信息:
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
产生错误的原因:在子组件中,你试图修改父组件通过props与子组件通信的数据。
两种解决方法:
将这个父组件传进来的要修改的数据,通过$emit再传回给父组件,在父组件中进行修改。
当父组件通过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;

浙公网安备 33010602011771号