类型错误:无法读取模板标记中 null 的属性
我在 Vue/Laravel 应用程序中收到“TypeError:无法读取 null 的属性”错误。我从API获取数据。我可以访问脚本标记中的数据,例如在安装方法中,但在模板中我无法访问数据。
<template>
<article class="hentry blog-post single-post single-post-v3">
<router-link :to="'/kategori/'+post.category.slug" class="post-category bg-primary">{{post.category.title}}</router-link>
<h1 class="post-title">{{post.title}}</h1>
...
</template>
<script>
export default {
components: {
FeaturedPosts,
Comments
},
async beforeRouteEnter(to, from, next) {
const returned = (await axios.get(route("api.post", to.params.slug))).data.response
next(vm => {
vm.post = returned.post;
vm.comments = (returned.comments != undefined) ? returned.comments.data : null;
vm.commentsPagination = (returned.comments != undefined) ? returned.comments : null;
});
},
data() {
return {
post: null,
comments: null,
commentsPagination: null,
};
},
}
</script>
它给出“未捕获(承诺中)类型错误:无法读取 null 的属性(读取“类别”)”。我可以在 Mounted() 方法中访问 post.category 但在模板中却不能。
I'm getting a "TypeError: Cannot read properties of null" error in my Vue/Laravel application. I get data from API. I can access data in the script tag for example in mounted method but in the template I can't access the data.
<template>
<article class="hentry blog-post single-post single-post-v3">
<router-link :to="'/kategori/'+post.category.slug" class="post-category bg-primary">{{post.category.title}}</router-link>
<h1 class="post-title">{{post.title}}</h1>
...
</template>
<script>
export default {
components: {
FeaturedPosts,
Comments
},
async beforeRouteEnter(to, from, next) {
const returned = (await axios.get(route("api.post", to.params.slug))).data.response
next(vm => {
vm.post = returned.post;
vm.comments = (returned.comments != undefined) ? returned.comments.data : null;
vm.commentsPagination = (returned.comments != undefined) ? returned.comments : null;
});
},
data() {
return {
post: null,
comments: null,
commentsPagination: null,
};
},
}
</script>
It gives "Uncaught (in promise) TypeError: Cannot read properties of null (reading 'category')". I can access post.category in mounted() method but in the template I can't.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
next(vm => ...)
回调在实例创建后触发,不应依赖在那里初始化的状态,因为初始渲染是在未初始化状态下发生的。它应该是:
或:
next(vm => ...)
callback is triggered after the instance is created, the state that is initialized there shouldn't be relied on because initial rendering occurs with uninitialized state.It should be either:
Or: