VUE报错: 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: “isShowData”;
原因: 直接在子组件修改了父组件的值
解决办法
在子组件不要修改父组件的值,用一个参数接收父组件的值,如下: 父组件:
<template>
<Card>
<child-properties-tab :cityList="cityList"
@on-after-save="afterSave"/>
</Card>
</template>
<script>
export default {
name: "child-properties-tab",
data() {
return {
cityList: [
{
value: 'New York',
label: 'New York'
},
{
value: 'London',
label: 'London'
}
],
}
},
}
</script>
子组件:
<template>
<div class="meta main" >
<Select v-model="model1" style="width:200px">
<Option v-for="item in cityList" :value="item.value"
:key="item.value" @on-change="onChange">{{ item.label }}</Option>
</Select>
</div>
</template>
<script>
export default {
name: "child-properties-tab",
props: [
"cityList"
]
data() {
return {
model1: ''
}
},
methods: {
onChange (v) {
if(v == 'London') {
this.cityList = [
{
value: 'New York',
label: 'New York'
},
{
value: 'London',
label: 'London'
},
{
value: 'shanghai',
label: 'shanghai'
}
];
}
}
}
}
</script>
上面的运行就会报错,修改子组件:
<script>
export default {
name: "child-properties-tab",
props: [
"cityList"
]
data() {
return {
model1: '',
cityData: this.cityList
}
},
methods: {
onChange (v) {
if(v == 'London') {
this.cityData = [......];
}
}
}
}
</script>
或者:computed
<script>
export default {
name: "child-properties-tab",
props: [
"cityList"
]
data() {
return {
cityData: [],
model1: ''
}
},
computed: {
cityData() {
return this.cityList;
}
},
methods: {
onChange (v) {
if(v == 'London') {
this.cityData = [......];
}
}
}
}
</script>
watch
export default {
name: "child-properties-tab",
props: [
"cityList"
]
data() {
return {
cityData: [],
model1: ''
}
},
watch: {
cityList(v) {
this.cityData = val;
}
},
methods: {
onChange (v) {
if(v == 'London') {
this.cityData = [.....];
}
}
}
}
</script>
|