问题:
parent.vue
<template>
<div>
父组件
<child :childObject="asyncObject"></child>
</div>
</template>
<script>
import child from ‘./child‘
export default {
data: () => ({
asyncObject: ‘‘
}),
components: {
child
},
created () {
},
mounted () {
// setTimeout模拟异步数据
setTimeout(() => {
this.asyncObject = {‘items‘: [1, 2, 3]}
console.log(‘parent finish‘)
}, 2000)
}
}
</script>
child.vue
<template>
<div>
子组件<!--这里很常见的一个问题,就是{{childObject}}可以获取且没有报错,但是{{childObject.items[0]}}不行,往往有个疑问为什么前面获取到值,后面获取不到呢?-->
<p>{{childObject.items[0]}}</p>
</div>
</template>
<script>
export default {
props: [‘childObject‘],
data: () => ({
}),
created () {
console.log(this.childObject) // 空值
},
methods: {
}
}
</script>
通常用v-if 解决 报错问题,以及create 的时候,childObject 值为空的问题
方式一 用 v-if 解决
parent.vue
<template>
<div>
父组件
<child :child-object="asyncObject" v-if="flag"></child>
</div>
</template>
<script>
import child from ‘./child‘
export default {
data: () => ({
asyncObject: ‘‘,
flag: false
}),
components: {
child
},
created () {
},
mounted () {
// setTimeout模拟异步数据
setTimeout(() => {
this.asyncObject = {‘items‘: [1, 2, 3]}
this.flag = true
console.log(‘parent finish‘)
}, 2000)
}
}
</script>
child.vue
<template>
<div>
子组件
<!--不报错-->
<p>{{childObject.items[0]}}</p>
</div>
</template>
<script>
export default {
props: [‘childObject‘],
data: () => ({
}),
created () {
console.log(this.childObject)// Object {items: [1,2,3]}
},
methods: {
}
}
</script>
方式二 用emit,on,bus组合使用
parent.vue
<template>
<div>
父组件
<child></child>
</div>
</template>
<script>
import child from ‘./child‘
export default {
data: () => ({
}),
components: {
child
},
mounted () {
// setTimeout模拟异步数据
setTimeout(() => {
// 触发子组件,并且传递数据过去
this.$bus.emit(‘triggerChild‘, {‘items‘: [1, 2, 3]})
console.log(‘parent finish‘)
}, 2000)
}
}
</script>
child.vue
<template>
<div>
子组件
<p>{{test}}</p>
</div>
</template>
<script>
export default {
props: [‘childObject‘],
data: () => ({
test: ‘‘
}),
created () {
// 绑定
this.$bus.on(‘triggerChild‘, (parmas) => {
this.test = parmas.items[0] // 1
this.updata()
})
},
methods: {
updata () {
console.log(this.test) // 1
}
}
}
</script>
这里使用了bus这个库,parent.vue和child.vue必须公用一个事件总线(也就是要引入同一个js,这个js定义了一个类似let bus = new Vue()的东西供这两个组件连接),才能相互触发 (ps:代码如下,需要安装依赖)
import VueBus from ‘vue-bus‘
Vue.use(VueBus)