一、props不为对象
//子组件中不能修改props传入的值 会引发vue报错 一般在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>
当父组件修改props的值时子组件中值跟随改变;当子组件中值改变时 报错 且父组件值无变化;
二、props为对象
//修改props传入对象属性即可 父组建属性跟随改变( 同样不能直接修改整个对象 )
<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>
父子组件修改值时相互影响