一、props不為對(duì)象
//子組件中不能修改props傳入的值 會(huì)引發(fā)vue報(bào)錯(cuò) 一般在mounted之后將其值賦予新的變量
<template>
<div>
<p>I Am The Data Of Parent: {{ parentData }}</p>
<child :childData="parentData "></child>
</div>
</template>
<script>
import Vue from 'vue';
const child = Vue.extend({
template: '<p>I Am The Data Of Child: {{ childData}}</p>',
props: {
childData: { type: String, required: true }
},
methods: {
changeChildData() {
setTimeout(() => {
this.childData = 'newnewnew';
}, 1000);
}
},
mounted() {
this.changeChildData();
}
});
export default {
data() {
return { parentData: 'oldoldold' };
},
methods: {
changeParentData() {
setTimeout(() => {
this.parentData = 'pnewpnewpnew';
}, 666);
}
},
mounted() {
this.changeParentData();
},
componts: { child }
};
</script>
當(dāng)父組件修改props的值時(shí)子組件中值跟隨改變;當(dāng)子組件中值改變時(shí) 報(bào)錯(cuò) 且父組件值無變化;
二、props為對(duì)象
//修改props傳入對(duì)象屬性即可 父組建屬性跟隨改變( 同樣不能直接修改整個(gè)對(duì)象 )
<template>
<div>
<p>I Am The Data Of Parent: {{ parentData.data }}</p>
<child :childData="parentData "></child>
</div>
</template>
<script>
import Vue from 'vue';
const child = Vue.extend({
template: '<p>I Am The Data Of Child: {{ childData.data }}</p>',
props: {
childData: { type: Object, required: true }
},
methods: {
changeChildData() {
setTimeout(() => {
// this.childData = { **** }; error
this.childData.data = 'newnewnew';
}, 1000);
}
},
mounted() {
this.changeChildData();
}
});
export default {
data() {
return { parentData: { data: 'oldoldold' } };
},
methods: {
changeParentData() {
setTimeout(() => {
// this.parentData = { **** }; run
this.parentData.data = 'pnewpnewpnew';
}, 666);
}
},
mounted() {
this.changeParentData();
},
componts: { child }
};
</script>
父子組件修改值時(shí)相互影響