詳解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默認(rèn)值為空,那么還是導(dǎo)致,child.vue這里報0的錯
<template>
<div>
子組件
<p>{{item0}}</p>
<p>{{item}}</p>
</div>
</template>
不過根據(jù)以上的案例,得出來一個問題就是異步更新值的問題,就是說開始的時候有個默認(rèn)值,這個默認(rèn)值會被異步數(shù)據(jù)改變,比如說這個異步數(shù)據(jù)返回的object,如果你用props的方式去傳遞這個數(shù)據(jù),其實第一次傳遞的空值,第二次傳遞的是更新后的值,所以就出現(xiàn){{childObject.items[0]}}類似這種取不到值的問題,既然說第一次是空值,它會這樣處理''.items[0],那么我們是不是可以在html判斷這個是不是空(或者在computed來判斷是否為默認(rèn)值),所以把案例二的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)代碼,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-03-03
ant desing vue table 實現(xiàn)可伸縮列的完整例子
最近在使用ant-design-vue做表格時,遇到要做一個可伸縮列表格的需求,在網(wǎng)上一直沒有找到好的方法,于是小編動手自己寫個可以此功能,下面小編把a(bǔ)nt desing vue table 可伸縮列的實現(xiàn)代碼分享到腳本之家平臺供大家參考2021-05-05
Vue2.x中的父組件傳遞數(shù)據(jù)至子組件的方法
這篇文章主要介紹了Vue2.x中的父組件數(shù)據(jù)傳遞至子組件的方法,需要的朋友可以參考下2017-05-05
Vue動態(tài)獲取數(shù)據(jù)后控件不可編輯問題
這篇文章主要介紹了Vue動態(tài)獲取數(shù)據(jù)后控件不可編輯問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-04-04

