如何在Vue中获取基于Laravel API资源的数据

时间:2018-08-07 03:06:54

标签: laravel vue.js

我正尝试显示user_id列与auth()->user()->id匹配的用户项目列表。

我的问题是如何定义资源路由要使用的功能。

代码

Controller

class ProjectController extends Controller
{
    public function index()
    {
        $projects = Project::orderby('id', 'desc')->latest()->take(10)->get();
        return response()->json($projects);
    }

    public function userprojects()
    {
        $projects = Project::orderby('id', 'desc')->where('user_id', '=', Auth::user()->id)->get();
        return $projects;
    }
}

Api route

Route::resource('projects', 'Api\ProjectController', ['except' => ['create', 'edit', 'destroy']]);

Vue component

<template>
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">Your Published Projects <span class="badge badge-info">{{projects.length}}</span></div>

                <div class="card-body">
                    <ul>
                        <li v-for="project in projects" :key="project.id">
                            {{project.title}} - {{project.user_id}}
                        </li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
export default {
    data(){
        return {
            projects: []
        }
    },
    created(){
            this.fetchProjects();
        },
        methods:{
            fetchProjects(){
                var self = this;
                axios.get('api/projects')
                    .then(function (resp) {
                        self.projects = resp.data;
                })
                .catch(function (resp) {
                    console.log(resp);
                        alert("Could not load projects");
                });
            },
        },
}
</script>

问题

  1. 如何告诉我的组件不要加载index函数而是要加载 来自userprojects函数的数据?

2 个答案:

答案 0 :(得分:0)

因此您可以添加一条新路线

Route::get('projects-user', 'Api\ProjectController@userprojects')->name('userprojects');

在js中。

axios.get(Router('userprojects').url()).then(response => {
    this.userprojects= response.data;
});

您也可以在控制器中执行此操作

class ProjectController extends Controller
{
    public function index()
    {
      if(Auth::check()){
        $projects = Project::orderby('id', 'desc')->where('user_id', '=', Auth::user()->id)->get();
      }else{
        $projects = Project::orderby('id', 'desc')->latest()->take(10)->get();
      }

        return response()->json($projects);
    }

}

答案 1 :(得分:0)

您可以在资源路由之前创建一个新路由并使用它:

Route::get('projects/me', 'Api\ProjectController@userprojects', ['except' => ['create', 'edit', 'destroy']]);
Route::resource('projects', 'Api\ProjectController', ['except' => ['create', 'edit', 'destroy']]);

然后在您的组件上

axios.get('api/projects/me')
.then(function (resp) {
    self.projects = resp.data;
})