【发布时间】:2020-02-01 09:51:53
【问题描述】:
我正在创建博客评论系统,我想为使用 vue.js 的帖子显示 cmets。 在控制台中,它说
属性或方法“注释”未在实例上定义,但 在渲染期间引用。
另外,当我尝试捕获用户名时,我得到了这个错误
渲染错误:“TypeError:无法读取未定义的属性‘用户’”
我想显示对特定帖子发表评论的 cmets 和用户
在 show.blade.php 中。
web.php
Route::get('results/{post}', 'ResultsController@show')->name('posts.show');
结果控制器
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;
//return $post->comments()->paginate(5); it returns objects
return view('posts.show',compact('posts'));
}
评论.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}`).then(({ data }) => {
this.comments = data
})
}
}
}
show.blade.php
<comments-component :post="{{ $posts['particular_post']->comments }}"></comments-component>
迁移表
Schema::create('comments', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('user_id');
$table->integer('post_id');
$table->text('body');
$table->integer('comment_id')->nullable();
$table->timestamps();
});
comment.php,我有这个。
protected $with = ['user'];
【问题讨论】:
-
您是否尝试过检查 ResultsController@show 是否返回所需的数据?
-
我做了,我把 return $post->cmets()->paginate(5);在控制器中,我可以看到 5 个对象。
-
console.log 在您的 api 回调中记录
data对象并检查data对象。我认为应该是 this.cmets = data.data。 (首先检查您的数据对象) -
您使用相同的端点来显示视图并获取 cmets。因此,当调用
fetchComment()方法时,您的ResultsController@show不会返回 JSON,而是返回包含您的视图的 HTML。尝试创建一个专用端点,以 JSON 格式返回某个帖子的 cmets。 -
@JulioMotol 我添加了一个新端点 Route::get('results/{post}/cmets', 'CommentsController@index');并像这样(
/results/${this.post.id}/comments)进行了更改,但没有成功。
标签: javascript php laravel vue.js fetch