1. 程式人生 > >Vue 父子組件傳遞方式

Vue 父子組件傳遞方式

pos prop itl component this min margin top methods

問題:

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)



來自為知筆記(Wiz)

Vue 父子組件傳遞方式