最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

詳解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)這樣的報錯,原因同上

復制代碼 代碼如下:

[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默認值為空,那么還是導致,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)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Vue寶典之this.$refs屬性的使用

    Vue寶典之this.$refs屬性的使用

    Vue.js中的refs屬性是一個非常有用的特性,它允許我們在組件中操作 DOM 元素和組件實例,本文來介紹一下Vue寶典之this.$refs屬性的使用,感興趣的可以了解一下
    2023-12-12
  • ant?design?vue的form表單取值方法

    ant?design?vue的form表單取值方法

    這篇文章主要介紹了ant?design?vue的form表單取值方法,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-06-06
  • vue使用自定義指令來控制頁面按鈕組的權(quán)限思想

    vue使用自定義指令來控制頁面按鈕組的權(quán)限思想

    這篇文章主要介紹了vue使用自定義指令來控制頁面按鈕組的權(quán)限思想,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-08-08
  • vue3 provide與inject的使用小技巧分享

    vue3 provide與inject的使用小技巧分享

    這篇文章主要介紹了vue3 provide與inject的使用小技巧,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-04-04
  • vue 表單之通過v-model綁定單選按鈕radio

    vue 表單之通過v-model綁定單選按鈕radio

    這篇文章主要介紹了vue 表單之v-model綁定單選按鈕radio的實例代碼,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下
    2019-05-05
  • vue修改Element的el-table樣式的4種方法

    vue修改Element的el-table樣式的4種方法

    這篇文章主要介紹了vue修改Element的el-table樣式的4種方法,幫助大家更好的理解和使用vue,感興趣的朋友可以了解下
    2020-09-09
  • 使用Vite+Vue3+TypeScript?搭建開發(fā)腳手架的詳細過程

    使用Vite+Vue3+TypeScript?搭建開發(fā)腳手架的詳細過程

    這篇文章主要介紹了Vite+Vue3+TypeScript?搭建開發(fā)腳手架的詳細過程,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2023-02-02
  • VUE3中watch和watchEffect的用法詳解

    VUE3中watch和watchEffect的用法詳解

    本文主要介紹了VUE3中watch和watchEffect的用法詳解,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-02-02
  • vue組件tabbar使用方法詳解

    vue組件tabbar使用方法詳解

    這篇文章主要為大家詳細介紹了vue組件tabbar使用方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-11-11
  • vue.js或js實現(xiàn)中文A-Z排序的方法

    vue.js或js實現(xiàn)中文A-Z排序的方法

    下面小編就為大家分享一篇vue.js或js實現(xiàn)中文A-Z排序的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-03-03

最新評論

天祝| 博客| 崇文区| 烟台市| 苗栗市| 进贤县| 嘉荫县| 体育| 宝山区| 隆化县| 兴化市| 安宁市| 武山县| 绥化市| 磐石市| 响水县| 青铜峡市| 安化县| 南乐县| 临海市| 漳平市| 定陶县| 阳江市| 广灵县| 三都| 股票| 曲阜市| 武强县| 余庆县| 武冈市| 江华| 筠连县| 南昌县| 陆良县| 五常市| 筠连县| 许昌市| 含山县| 镇平县| 思茅市| 阳城县|