Vue 父子组件传递方式
生活随笔
收集整理的這篇文章主要介紹了
Vue 父子组件传递方式
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
問題:
parent.vue
<template>
<div>
父組件
<child :childObject="asyncObject"></child>
</div>
</template>
<script>
import child from './child'
export default {
data: () => ({
asyncObject: ''
}),
components: {
child
},
created () {
},
mounted () {
// setTimeout模擬異步數(shù)據(jù)
setTimeout(() => {
this.asyncObject = {'items': [1, 2, 3]}
console.log('parent finish')
}, 2000)
}
}
</script>
child.vue
<template>
<div>
子組件<!--這里很常見的一個(gè)問題,就是{{childObject}}可以獲取且沒有報(bào)錯(cuò),但是{{childObject.items[0]}}不行,往往有個(gè)疑問為什么前面獲取到值,后面獲取不到呢?-->
<p>{{childObject.items[0]}}</p>
</div>
</template>
<script>
export default {
props: ['childObject'],
data: () => ({
}),
created () {
console.log(this.childObject) // 空值
},
methods: {
}
}
</script>
通常用v-if 解決 報(bào)錯(cuò)問題,以及create 的時(shí)候,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模擬異步數(shù)據(jù)
setTimeout(() => {
this.asyncObject = {'items': [1, 2, 3]}
this.flag = true
console.log('parent finish')
}, 2000)
}
}
</script>
child.vue
<template>
<div>
子組件
<!--不報(bào)錯(cuò)-->
<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模擬異步數(shù)據(jù)
setTimeout(() => {
// 觸發(fā)子組件,并且傳遞數(shù)據(jù)過去
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這個(gè)庫,parent.vue和child.vue必須公用一個(gè)事件總線(也就是要引入同一個(gè)js,這個(gè)js定義了一個(gè)類似let bus = new Vue()的東西供這兩個(gè)組件連接),才能相互觸發(fā) (ps:代碼如下,需要安裝依賴)
import VueBus from 'vue-bus'
Vue.use(VueBus)
來自為知筆記(Wiz)
總結(jié)
以上是生活随笔為你收集整理的Vue 父子组件传递方式的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 还在用AIDL吗?试试EasyMesse
- 下一篇: UVAL 4728 Squares(旋转