問題:
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)