我正在使用 vue.js 和 laravel5.8 创建评论系统。
我已经完成了模型和播种,所以我现在有 10 条评论到一个帖子(id 是 51)。
但是我得到了这个错误,
Property or method "comment" is not defined on the instance but referenced during render
和
Cannot read property 'user' of undefined
我在获取数据时遇到问题。
我为评论功能创建了一个新端点。 网页.php
Route::get('results/{post}', 'ResultsController@show')->name('posts.show');
Route::get('results/{post}/comments', 'CommentsController@index');
我想在 show.blade.php 中显示评论。
ResultsController.php
public function show(Post $post)
{
$recommended_posts = Post::latest()
->whereDate('date','>',date('Y-m-d'))
->where('category_id','=',$post->category_id)
->where('id','!=',$post->id)
->limit(7)
->get();
$posts['particular_post'] = $post;
$posts['recommended_posts'] = $recommended_posts;
$post->comments()->with('user')->get();
return view('posts.show',compact('posts'));
}
显示.blade.php
<comments-component :post="{{ $posts['particular_post']->comments }}"></comments-component>
评论.vue
<div class="reply-comment" :v-for="comment in comments">
<div class="user-comment" >
<div class="user">
<!--<img src="" alt="" >-->
<avatar :username="comment.user.name" :size="30" ></avatar>
</div>
<div class="user-name">
<span class="comment-name">{{ comment.user.name }}</span>
<p> {{ comment.body }} </p>
</div>
</div>
<div class="reply">
<div class="seemorecomments">
<a href="">see more</a>
</div>
<button class="reply-button">
<i class="fas fa-reply"></i>
</button>
</div>
</div>
<script>
import Avatar from 'vue-avatar'
export default {
props: ['post'],
components: {
Avatar
},
mounted() {
this.fetchComments()
},
data: () => ({
comments: {
data: []
}
}),
methods: {
fetchComments() {
axios.get(`/results/${this.post.id}/comments`).then(({data}) => {
this.comments = data
})
}
}
}
评论 Controller .php
public function index(Post $post)
{
return $post->comments()->paginate(5);
$post->comments()->with('user')->get();
}
评论.php
protected $with = ['user'];
最佳答案
在 axios 中,您可能需要从返回的响应中访问 data
(请参阅 console.log
examples here),请在您的 comments
组件中尝试以下操作:
methods: {
fetchComments() {
axios.get(`/results/${this.post.id}/comments`).then((response) => {
this.comments = response.data.data
})
}
}
注意使用response.data.data
。
我假设返回 ->paginate()
会将结果放入返回数组的 data
键中。如果没有,则只需使用 response.data
。
此外,在获取评论的 Controller 中更改为以下内容:
public function index(Post $post)
{
return $post->comments()->with('user')->paginate(5);
}
这将预先加载用户查询的评论。
关于javascript - Laravel 5 vue.js : Property or method "comment" is not defined on the instance but referenced during render,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58217427/