如何使用Vue获取与帖子相关的评论

时间:2016-03-15 05:31:36

标签: laravel laravel-5 vue.js

我正在与Laravel建立一个论坛,正如标题所说我想使用Vue.js从我的数据库中的某个帖子上留下评论,并在我的节目页面上显示它们。

我使用下面的网址显示某个帖子

Route::get('forums/{category_id}/{title}','ForumsController@show');

以下代码不起作用。非常感谢任何帮助。

ps.我正在使用Vue.resource。

论坛控制器

Route::get('forums','ForumsController@index');
Route::get('forums/create','ForumsController@create');
Route::post('forums', 'ForumsController@store');
Route::get('forums/{category_id}/{title}','ForumsController@show');
Route::get('forums/{category_id}','ForumsController@showByCategory');
Route::get('forums/{id}/{title}/edit','ForumsController@edit');
Route::patch('forums/{id}/{title}','ForumsController@update');
Route::delete('forums/destroy','ForumsController@destroy');
Route::post('forums/{category_id}/{title}', 'ForumsController@saveReply');

//API
Route::get('api/posts/{category_id}/{title}', function($category_id, $title){
    return App\Topic::with('comments')->where(compact('category_id','title'))->firstOrFail();
});

Vue的

new Vue({


el: '#comment', 

methods: {

    fetchComment: function (category_id, title) {
        this.$http.get('/api/posts/' + category_id + '/' + title ,function (data) {
            this.$set('topics',data)
        })
    }


},





ready: function () {
    this.fetchComment()
}

})

show.blade.php

@extends('app')
@section('content')
    <div id="comment">
        <ul v-for="comment in posts">
            <li>@{{comment.reply}}</li>
        </ul>
    </div>
@stop    

发表表格

public function up(){
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');$table->integer('category_id')->unsigned();
$table->integer('user_id')->unsigned();
$table->string('title');
$table->text('body');
$table->timestamps();
});

评论表

public function up()
{
    Schema::create('comments', function (Blueprint $table) {
        $table->increments('id');
        $table->text('reply');
        $table->integer('user_id')->unsigned();


        $table->integer('topic_id')->unsigned();
        $table->foreign('topic_id')->refrenced('id')->on('topics')->onDelete('cascade');

        $table->timestamps();

显示某个帖子的方法

public function show($category_id, $title)
{

   $topic = Topic::where(compact('category_id','title'))->firstOrFail();

   $comments = Comment::where('topic_id',$topic->id)->get();

    return view('forums.category', compact('topic','comments'));
}

感谢Jeff帮助我

我像这样修改了

fetchComment: function (category_id, title) {
        this.$http.get('/api/topics/' + category_id + '/' + title ,function (data) {
            this.$set('topics',data)
        })
    }

ready: function () {
    this.fetchComment(category_id, title)
}

但我收到此错误消息

http://my-sitename/api/topics/undefined/undefined 404 (Not Found)

我是一个完整的菜鸟,所以任何帮助都会非常感激

1 个答案:

答案 0 :(得分:0)

你的函数fetchComment有2个参数,你没有发送任何参数。

fetchComment: function (category_id, title)

ready: function () {
  this.fetchComment() //needs arguments
}