欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳解vue2父組件傳遞props異步數(shù)據(jù)到子組件的問題

 更新時間:2017年06月29日 10:21:31   作者:無盡_故事  
本篇文章主要介紹了vue2父組件傳遞props異步數(shù)據(jù)到子組件的問題,具有一定的參考價值,感興趣的小伙伴們可以參考一下

測試環(huán)境:vue v2.3.3, vue v2.3.1

案例一

父組件parent.vue

// asyncData為異步獲取的數(shù)據(jù),想傳遞給子組件使用
<template>
 <div>
  父組件
  <child :child-data="asyncData"></child>
 </div>
</template>

<script>
 import child from './child'
 export default {
  data: () => ({
   asyncData: ''
  }),
  components: {
   child
  },
  created () {
  },
  mounted () {
   // setTimeout模擬異步數(shù)據(jù)
   setTimeout(() => {
    this.asyncData = 'async data'
    console.log('parent finish')
   }, 2000)
  }
 }
</script>

子組件child.vue

<template>
 <div>
  子組件{{childData}}
 </div>
</template>

<script>
 export default {
  props: ['childData'],
  data: () => ({
  }),
  created () {
   console.log(this.childData) // 空值
  },
  methods: {
  }
 }
</script>

上面按照這里的解析,子組件的html中的{{childData}}的值會隨著父組件的值而改變,但是created里面的卻不會發(fā)生改變(生命周期問題)

案例二

parent.vue

<template>
 <div>
  父組件
  <child :child-object="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>
  子組件<!--這里很常見的一個問題,就是{{childObject}}可以獲取且沒有報錯,但是{{childObject.items[0]}}不行,往往有個疑問為什么前面獲取到值,后面獲取不到呢?-->
  <p>{{childObject.items[0]}}</p>
 </div>
</template>

<script>
 export default {
  props: ['childObject'],
  data: () => ({
  }),
  created () {
   console.log(this.childObject) // 空值
  },
  methods: {
  }
 }
</script>

created里面的卻不會發(fā)生改變, 子組件的html中的{{{childObject.items[0]}}的值雖然會隨著父組件的值而改變,但是過程中會報錯

// 首先傳過來的是空,然后在異步刷新值,也開始時候childObject.items[0]等同于''.item[0]這樣的操作,所以就會報下面的錯
vue.esm.js?8910:434 [Vue warn]: Error in render function: "TypeError: Cannot read property '0' of undefined"

針對二的解決方法:

使用v-if可以解決報錯問題,和created為空問題

// 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>
  子組件
  <!--不報錯-->
  <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>

子組件使用watch來監(jiān)聽父組件改變的prop,使用methods來代替created

parent.vue

<template>
 <div>
  父組件
  <child :child-object="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>
  子組件<!--1-->
  <p>{{test}}</p>
 </div>
</template>

<script>
 export default {
  props: ['childObject'],
  data: () => ({
   test: ''
  }),
  watch: {
   'childObject.items': function (n, o) {
    this.test = n[0]
    this.updata()
   }
  },
  methods: {
   updata () { // 既然created只會執(zhí)行一次,但是又想監(jiān)聽改變的值做其他事情的話,只能搬到這里咯
    console.log(this.test)// 1
   }
  }
 }
</script>

子組件watch computed data 相結(jié)合,有點麻煩

parent.vue

<template>
 <div>
  父組件
  <child :child-object="asyncObject"></child>
 </div>
</template>

<script>
 import child from './child'
 export default {
  data: () => ({
   asyncObject: undefined
  }),
  components: {
   child
  },
  created () {
  },
  mounted () {
   // setTimeout模擬異步數(shù)據(jù)
   setTimeout(() => {
    this.asyncObject = {'items': [1, 2, 3]}
    console.log('parent finish')
   }, 2000)
  }
 }
</script>

child.vue

<template>
 <div>
  子組件<!--這里很常見的一個問題,就是{{childObject}}可以獲取且沒有報錯,但是{{childObject.items[0]}}不行,往往有個疑問為什么前面獲取到值,后面獲取不到呢?-->
  <p>{{test}}</p>
 </div>
</template>

<script>
 export default {
  props: ['childObject'],
  data: () => ({
   test: ''
  }),
  watch: {
   'childObject.items': function (n, o) {
    this._test = n[0]
   }
  },
  computed: {
   _test: {
    set (value) {
     this.update()
     this.test = value
    },
    get () {
     return this.test
    }
   }
  },
  methods: {
   update () {
    console.log(this.childObject) // {items: [1,2,3]}
   }
  }
 }
</script>

使用emit,on,bus相結(jié)合

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這個庫,parent.vue和child.vue必須公用一個事件總線(也就是要引入同一個js,這個js定義了一個類似let bus = new Vue()的東西供這兩個組件連接),才能相互觸發(fā)

使用prop default來解決{{childObject.items[0]}}

parent.vue

<template>
 <div>
  父組件
  <child :child-object="asyncObject"></child>
 </div>
</template>

<script>
 import child from './child'
 export default {
  data: () => ({
   asyncObject: undefined // 這里使用null反而報0的錯
  }),
  components: {
   child
  },
  created () {
  },
  mounted () {
   // setTimeout模擬異步數(shù)據(jù)
   setTimeout(() => {
    this.asyncObject = {'items': [1, 2, 3]}
    console.log('parent finish')
   }, 2000)
  }
 }
</script>

child.vue

<template>
 <div>
  子組件<!--1-->
  <p>{{childObject.items[0]}}</p>
 </div>
</template>

<script>
 export default {
  props: {
   childObject: {
    type: Object,
    default () {
     return {
      items: ''
     }
    }
   }
  },
  data: () => ({
  }),
  created () {
   console.log(this.childObject) // {item: ''}
  }
 }
</script>

在說用vuex解決方法的時候,首先看看案例三

案例三

main.js

import Vue from 'vue'
import App from './App'
import router from './router'
import VueBus from 'vue-bus'
import index from './index.js'
Vue.use(VueBus)

Vue.config.productionTip = false
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
 modules: {
  index
 }
})
/* eslint-disable no-new */
new Vue({
 el: '#app',
 store,
 router,
 template: '<App/>',
 components: { App }
})

index.js

const state = {
 asyncData: ''
}

const actions = {
 asyncAction ({ commit }) {
  setTimeout(() => {
   commit('asyncMutation')
  }, 2000)
 }
}
const getters = {
}

const mutations = {
 asyncMutation (state) {
  state.asyncData = {'items': [1, 2, 3]}
 }
}

export default {
 state,
 actions,
 getters,
 mutations
}

parent.vue

<template>
 <div>
  父組件
  <child></child>
 </div>
</template>

<script>
 import child from './child'
 export default {
  data: () => ({
  }),
  components: {
   child
  },
  created () {
   this.$store.dispatch('asyncAction')
  },
  mounted () {
  }
 }
</script>

child.vue

<template>
 <div>
  子組件
  <p>{{$store.state.index.asyncData.items[0]}}</p>
 </div>
</template>

<script>
 export default {
  data: () => ({
  }),
  created () {
  },
  methods: {
  }
 }
</script>

{{$store.state.index.asyncData.items[0]}}可以取到改變的值,但是過程中還是出現(xiàn)這樣的報錯,原因同上

復(fù)制代碼 代碼如下:

[Vue warn]: Error in render function: "TypeError: Cannot read property '0' of undefined"

所以這里的解決方法是:vuex結(jié)合computed、mapState或者合computed、mapGetters

parent.vue

<template>
 <div>
  父組件
  <child></child>
 </div>
</template>

<script>
 import child from './child'
 export default {
  data: () => ({
  }),
  components: {
   child
  },
  created () {
   this.$store.dispatch('asyncAction')
  },
  mounted () {
  }
 }
</script>

child.vue

<template>
 <div>
  子組件
  <p>{{item0}}</p>
  <p>{{item}}</p>
 </div>
</template>

<script>
 import { mapState, mapGetters } from 'vuex'
 export default {
  data: () => ({
   test: ''
  }),
  computed: {
   ...mapGetters({
    item: 'getAsyncData'
   }),
   ...mapState({
    item0: state => state.index.asyncData
   })
  },
  created () {
  },
  methods: {
  }
 }
</script>

index.js

const state = {
 asyncData: ''
}

const actions = {
 asyncAction ({ commit }) {
  setTimeout(() => {
   commit('asyncMutation', {'items': [1, 2, 3]})// 作為參數(shù),去調(diào)用mutations中的asyncMutation方法來對state改變
  }, 2000)
 }
}
const getters = {
 getAsyncData: state => state.asyncData
}

const mutations = {
 asyncMutation (state, params) {
  state.asyncData = params.items[0] // 此時params={'items': [1, 2, 3]}被傳過來賦值給asyncData,來同步更新asyncData的值,這樣html就可以拿到asyncData.items[0]這樣的值了
 }
}

export default {
 state,
 actions,
 getters,
 mutations
}

注意上面的

....
commit('asyncMutation', {'items': [1, 2, 3]})
...
state.asyncData = params.items[0]

如果寫成這樣的話

commit('asyncMutation')
state.asyncData = {'items': [1, 2, 3]}

首先asyncAction是個異步的操作,所以asyncData默認值為空,那么還是導(dǎo)致,child.vue這里報0的錯

<template>
 <div>
  子組件
  <p>{{item0}}</p>
  <p>{{item}}</p>
 </div>
</template>

不過根據(jù)以上的案例,得出來一個問題就是異步更新值的問題,就是說開始的時候有個默認值,這個默認值會被異步數(shù)據(jù)改變,比如說這個異步數(shù)據(jù)返回的object,如果你用props的方式去傳遞這個數(shù)據(jù),其實第一次傳遞的空值,第二次傳遞的是更新后的值,所以就出現(xiàn){{childObject.items[0]}}類似這種取不到值的問題,既然說第一次是空值,它會這樣處理''.items[0],那么我們是不是可以在html判斷這個是不是空(或者在computed來判斷是否為默認值),所以把案例二的child.vue

<template>
 <div>
  <p>{{childObject != '' ? childObject.items[0]: ''}}</p>
 </div>
</template>

<script>
 export default {
  props: ['childObject'],
  data: () => ({
  }),
  created () {
   console.log(this.childObject) // 空值
  },
  methods: {
  }
 }
</script>

這樣是可以通過不報錯的,就是created是空值,猜想上面vuex去stroe也可以也可以這樣做

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Vue-router編程式導(dǎo)航的兩種實現(xiàn)代碼

    Vue-router編程式導(dǎo)航的兩種實現(xiàn)代碼

    這篇文章主要介紹了Vue-router編程式導(dǎo)航的實現(xiàn)代碼,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-03-03
  • vue請求接口并且攜帶token的實現(xiàn)

    vue請求接口并且攜帶token的實現(xiàn)

    本文主要介紹了vue請求接口并且攜帶token的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-07-07
  • 在vue路由上添加公共的路由前綴方式

    在vue路由上添加公共的路由前綴方式

    這篇文章主要介紹了在vue路由上添加公共的路由前綴方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-12-12
  • Element Backtop回到頂部的具體使用

    Element Backtop回到頂部的具體使用

    這篇文章主要介紹了Element Backtop回到頂部的具體使用,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-07-07
  • ant desing vue table 實現(xiàn)可伸縮列的完整例子

    ant desing vue table 實現(xiàn)可伸縮列的完整例子

    最近在使用ant-design-vue做表格時,遇到要做一個可伸縮列表格的需求,在網(wǎng)上一直沒有找到好的方法,于是小編動手自己寫個可以此功能,下面小編把ant desing vue table 可伸縮列的實現(xiàn)代碼分享到腳本之家平臺供大家參考
    2021-05-05
  • Vue2.x中的父組件傳遞數(shù)據(jù)至子組件的方法

    Vue2.x中的父組件傳遞數(shù)據(jù)至子組件的方法

    這篇文章主要介紹了Vue2.x中的父組件數(shù)據(jù)傳遞至子組件的方法,需要的朋友可以參考下
    2017-05-05
  • vue 實現(xiàn)圖片懶加載功能

    vue 實現(xiàn)圖片懶加載功能

    這篇文章主要介紹了vue 實現(xiàn)圖片懶加載功能的方法,幫助大家更好的理解和使用vue,感興趣的朋友可以了解下
    2020-12-12
  • Vue動態(tài)獲取數(shù)據(jù)后控件不可編輯問題

    Vue動態(tài)獲取數(shù)據(jù)后控件不可編輯問題

    這篇文章主要介紹了Vue動態(tài)獲取數(shù)據(jù)后控件不可編輯問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-04-04
  • vue.js 實現(xiàn)輸入框動態(tài)添加功能

    vue.js 實現(xiàn)輸入框動態(tài)添加功能

    這篇文章主要介紹了vue.js 實現(xiàn)輸入框動態(tài)添加功能,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下
    2018-06-06
  • Vue仿支付寶支付功能

    Vue仿支付寶支付功能

    這篇文章主要介紹了Vue仿支付寶支付功能,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下
    2018-05-05

最新評論