laravel - 我收到此错误 TypeError: Cannot read property 'url' of null
问题描述
问题是当我渲染内容时,我需要调用 {{ post.image.url }} 但我得到这个问题“无法读取 null 的属性 'url'”</p>
这是我的代码:
data() {
return {
posts: null,
avatar: null
}
}
axios.get('/ajax/posts/' + user)
.then((response) => {
this.posts = response.data.posts;
this.avatar = response.data.avatar;
console.log(response.data.posts);
});
和我用于检索信息的 php 代码:
public function ajaxGetPosts($user)
{
$profile = User::findOrFail($user)->first();
//dd($user->posts()->withCount('image')->get());
$posts = $profile->posts()->with('image')->get();
return response()->json([
'posts' => $posts->toArray(),
'avatar' => $profile->getAvatar()
]);
}
结果 console.log 是:
{
"id":1,
"user_id":1,
"title":"Dolores voluptatem culpa dolor est.",
"body":"Iste et ratione atque inventore. Quo ex ea repellat saepe est ad est dicta. Magni eum omnis dolor quam provident mollitia.",
"created_at":"2020-03-22T16:04:47.000000Z",
"updated_at":"2020-03-22T16:04:47.000000Z",
"image": {
"id":1,
"url":"https://loremflickr.com/600/800",
"imageable_type":"App\\Post",
"imageable_id":1,
"created_at":"2020-03-22T16:57:14.000000Z",
"updated_at":"2020-03-22T16:57:14.000000Z"
}
}
解决方案
这些评论为您提供了解决问题的一些想法。这就是为什么:
当页面/组件加载时,如果您data
用于渲染模板,它将使用您定义的 init 数据渲染模板,这是null
在posts
您的代码中。
data
要解决此问题,您可以在 Vue 组件中为您的道具放置一些默认数据。喜欢
data() {
return {
posts:[{image:{url: "../assets/logo.png"}}],
}
}
或在模板中使用if
或。?:
我个人喜欢我的方式,这种方式可以让你知道你的数据结构是什么。使您的代码清晰且易于调试。