我试图找出为什么我似乎无法在我的Vue组件中访问以下JSON数据。
我的项目是使用Vue-cli和Webpack模板设置的,当我遇到问题时大致设置如下。
此文件包含多个项目
projects: [
{
"slug": "page-url-slug",
"title": "Page title",
"image": {
"src": "/static/images/project-image.jpg",
"alt": "Alt text image"
}
}
]
routes: [
{
path: '/work'
component: Work
},
{
path: '/work/:slug',
component: WorkItem,
props: (route) => ({
params: route.params
})
}
]
export default {
props: [ 'params' ],
data () {
return {
project: {}
}
},
mounted () {
this.$http.get('/static/data.json')
.then((response) => {
let projects = response.data.projects
// Find data with same slug param
for (let i = 0; i < projects.length; i++) {
if (projects[i].slug === this.params.slug) {
this.project = projects[i]
return
}
}
// Else go back to parent route
this.$router.push('/work')
})
}
}
<template lang="html">
<div class="page">
<h1>{{ project.title }}</h1>
<img :src="project.image.src" alt="project.image.alt" />
</div>
</template>
当我尝试访问 project.image.src 或 project.image.alt 时,我不断收到以下错误消息:
[Vue warn]: Error when rendering anonymous component at ...
Uncaught TypeError: Cannot read property 'src' of undefined
我对Vuejs很陌生,我似乎无法理解这种情况。
答案 0 :(得分:2)
在异步加载project
时必须添加空检查,如下所示:
<img :src="project && project.image && project.image.src" alt="project.image.alt" />
当呈现此内容时,当时project
未填充且仍为{}
,您在开头设置它。