更新数据库,laravel,vue js中的view_count col

时间:2019-05-30 01:59:32

标签: javascript laravel vuejs2

我正在尝试在每个view_count上更新@click列。但找不到正确的方法。

首先将控制器设为--resource,并通过api获取数据。

控制器:

public function index()
{
    $articles = Article::all();

    return response()->json([
        "articles" => $articles
    ], 200);
}

public function show($id)
{
    $article = Article::whereId($id)->first();

    return response()->json([
        "article" => $article
    ], 200);
}

也设置了更新功能。

public function update(Request $request, $id)
{
    $view = Article::find($id);
    $view->update($request->where("view_count"));
    return response()->json(["message" => "view_count updated"]);
}

我设置了api路由:

Route::get('/articles', 'ArticlesController@index');
Route::get('/articles/{id}', 'ArticlesController@show');
Route::get('/articles/{id}', 'ArticlesController@update');

最后是Vue.js

<p class="button">
   <i @click.prevent="count" class="fas fa-chevron-right"></i>
</p>

data(){
    return {
        view: 0,
    };
},
methods: {
    count: function(){
        axios.post("/api/articles" + this.item.id).then(response => {
            this.view++;
        })
        window.location.href = "pages/" + this.item.id

    }
}

它正在计数,但不更新列。另外,当我刷新页面时,它当然会从0开始计数……这并不是真正有效的方法。最好和正确的方法是什么?

谢谢。

不是:顺便说一下,我正在父组件中获取并迭代api:

<div class="listWrap" :key="item.id" v-for="item in filterArticles">
   <list :item="item" />
</div>

1 个答案:

答案 0 :(得分:1)

您更新视图的工作流程是错误的。

首先,我们应该将update方法的uri方法更改为GET,如下所示:

Route::get('/articles/update/{id}', 'ArticlesController@update');

然后,在update中使用我们的ArticlesController方法来增加view_count的值:

public function update(int $id)
{
   // i have changed the $view by $article
    $article = Article::find($id);
    $article->view_count++;
    $article->save();
    return response()->json(["message" => "view_count updated", 201]);
}

在我们的Vue组件中,我们应该更新update方法的URI和HTTP方法名称,因为我们应该在客户端和服务器端使用相同的HTTP动词。

    <p class="button">
       <i @click.prevent="count" class="fas fa-chevron-right"></i>
    </p>

    <script>
    export default {
// as you are using parent/child relationship betwen components, you should use props.
        props: { item: Object },
        data(){
            return {
                view: 0,
            };
        },
        methods: {
            count: function(){
                axios.get(`/api/articles/update/${this.item.id}`).then(response => {
                    this.view++;
                })
                window.location.href = "pages/" + this.item.id;
            }
        } 
    }
    </script>