【浅谈】Vue中关于父子组件传对象值的问题(一)
1.父组件parent.vue
<template>
<div>
<children :option="cOption"></children>
</div>
</template>
<script>
import children from "./children"
export default {
components:{children},
data(){
return {
cOption:{
aObj:'a',
bObj:{
bbObj:'11'
}
}
}
},
methods:{}
}
</script>
2.子组件children.vue
用官方推荐的computed和watch组合拳
<template>
<div>
</div>
</template>
<script>
export default {
data(){
return {
}
},
computed:{
getOption(){
console.log(this.option)
return this.option;
}
},
watch:{
getOption(val){
console.log(val)
}
}
}
</script>
Ⅰ.以上最基本的写法,最终控制台输出显示执行了computed内的语句
Ⅱ.如果要输出watch的console.log
watch:{
getOption:{
handler:function(val) {
console.log(val)
},
immediate:true
}
}
此时,父组件改变传值
this.cOption.bObj.bbObj = '22'
children 没有感知
Ⅲ.继续改造children的watch
watch:{
getOption:{
handler:function(val) {
console.log(val)
},
immediate:true,
deep:true
}
}
控制台输出watch 的语句
希望对你有所帮助