在子component中使用props接收父component的数据,是在不包含vuex的项目中跨层级component数据传输的常规操作。
然而,这里并不总是一帆风顺的。在实际操作中,如果父component的某个属性对应的值并非静态定义的,而是通过异步接口获取的,子component直接用props引用,并在template中进行标签绑定,就很可能会出现问题。
现来看正常情况下的代码————
father component
<template>
<div id='father'>
<p>This is father-component</p>
<child-component :list="sublist"></child-component>
</div>
</template>
<script>
import child from './ChildComponent'
export default {
name: 'father',
components: {
child
},
data () {
return {
sublist: [
{
title: "First",
imgurl: "http://.../first.jpg"
},
{
title: "Second",
imgurl: "http://.../second.jpg"
},
{
title: "Third",
imgurl: "http://.../third.jpg"
},
]
}
},
...
}
</script>
child component
<template>
<div id='child'>
<ul>
<li class='list-item' v-for="(item, index) in list" :key="`item-${index}`">{{ item.title }}
<img :src="item.imgurl">
</li>
</ul>
</div>
</template>
<script>
export default {
name: 'child',
props: ['list'],
...
}
</script>
以上代码中,childComponent
通过fatherComponent
的sublist
属性绑定到list
的props上,并遍历其渲染<li>
列表元素。此时我们的代码是能够正常运行的。
但是,很多情况下,尤其是在涉及到根组件初始化时的数据来源时,我们往往并不是使用硬编码好的数据进行存储,而是通过接口异步获取data,再给根组件的属性进行赋值。
还以上面的代码为主结构,假定我们全局已经引入了axios作为接口获取库,并进行了绑定 Vue.prototype.$http = axios
,fatherComponent
的代码修改如下————
<script>
import child from './ChildComponent'
export default {
name: 'father',
components: {
child
},
data () {
return {
sublist: []
}
},
mounted: {
this.$http.get('http://.../..').then((resp) => {
this.sublist = resp.data.sublist
}).catch((err) => {
console.log(`获取接口错误——${err}`)
})
},
...
}
</script>
此时,我们将fatherComponent
的数据初始化为空Array,硬编码修改为了异步使用axios通过接口获取再赋值。如果childComponent
的代码依旧不做任何改动,再运行,将会报错,报错内容如下
[Vue warn]: Error in render: "TypeError: Cannot read property 'title' of undefined"
并且在console的报错日志中,我们可以通过调用栈跟踪到,在<li>
元素绑定props时报出了上述错误。
为什么呢?
事实上,在子元素渲染的时,就已经通过props去获取父组件传进来的数据了。然而此时,异步获取的数据尚未拿到并传入,但是子元素的mounted只会在最初执行一次,因此,渲染时所使用的props其实是一个空数组,所以绑定的每一个item都是undefined,当然无法获取到其title。**
通常,我们可以通过给childComponent
增加一个watch
观察器对props
的list
进行变化监控,但其实在常见情况下,该问题还有一个比较简便的解决方案————
给childComponent的渲染增加条件,
v-if
条件渲染。我们在fatherComponent
中插入childComponent
时可以写成如下形式
<template>
<div id='father'>
<p>This is father-component</p>
<child-component v-if="sublist.length" :list="sublist"></child-component>
</div>
</template>
通过v-if判断当前father
的sublist
是否含有内容,如果有内容,才对childComponent进行渲染,否则不渲染。
这样,只有当异步获取的数据填入sublist中之后,sublist.length
不再为0,才会对childComponent
进行渲染,childComponent
中的list
包含的item才能以对象的形式被取到title和imgurl属性的值。