它为什么没有显示通过标题和描述的任何错误,但是显示了渲染错误: content.link.text上的“ TypeError:无法读取未定义的属性'text'”
父母
<template>
<div>
<splash :content="Splash"></splash>
</div>
</template>
<script>
import Child from './Child.vue'
export default {
name: 'Main',
data () {
Splash: {},
},
created () {
const ax = axios.create({
baseURL: '/static'
})
ax.get('content.json')
.then(res => {
this.Splash = res.data.general.splash
})
},
components: {
Splash
}
}
</script>
儿童
<template>
<div class="container">
<h2>{{ content.title }}</h2> // ok
<p>{{ content.description }}</p> // ok
<p>{{ content.link.text }}</p> // shows render error
</div>
</template>
<script>
export default {
name: 'Splash',
props: [
'content'
]
}
</script>
content.json
{
general : {
splash : {
"title" : "lorem title",
"description" : "lorem description",
"link" : {
"text" : "click me"
}
}
}
}
这很可能是由于content
首次渲染的值所致。那是一个空对象,它将为任何属性返回undefined
content = {}
link = content.link // link is undefined
link.text // error
您应该具有首先渲染的条件,以便除非内容具有有效值,否则您不会显示该内容。
扩展中
您的承诺在创建的钩子中,但是由于它是异步的,因此它将仅在当前同步周期结束后的某个时候返回数据。到那时,已经使用将导致错误的对象创建了Splash组件。
如果要执行这样的模式以获取实际数据,则可以使用几种模式,具体取决于您希望用户流如何工作。
使用lodash _.get包装可能存在或可能不存在的所有数据。然后,您content.link.text
将进入计算出的属性,并且类似return _.get(content, 'link.text')
。这将导致它在此处正确返回一个值。
在异步请求完成之前不要渲染Splash,在加载时显示加载
在Splash组件中使用v-if进行防护
在这些问题中,我想说2是最好的账单,它消除了人们的担忧。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句