普通网友 2018-05-12 15:59
浏览 184
已采纳

Laravel,Vue.js数组空

I'm totally new to the laravel and vue.js frameworks. For a school project with have to create an app that uses laravel for the back-end and vue.js for the front-end. So I created an API to use it afterwards in my vue.Js. But the problem is that when I want to get the data in my Vue.JS it tells me it has an empty array which should show all the values I have in my database (about 20). I have been struggling since 2 days on it and now, I'm totally lost, I don't know what to do or what goes wrong.. I tried my API into postman and it works perfect.

Specs: -> Laravel 5.6 -> Vue 2.5.7

My API Controller:

    <?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Note;
use App\Http\Resources\Note as NoteResource;

class NotesApiController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $notes = Note::all();
        return NoteResource::collection($notes);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $note = new Note;
        $note->user_id = $request -> input('user_id');
        $note->course_id = $request -> input('course_id');
        $note->title = $request -> input('title');
        $note->body = $request -> input('body');
        $note->file_name = $request -> input('file_name');
        $note->save();
        return new NoteResource($note);
        return response() -> json('success', 200);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $note = Note::findOrFail($id);
        return new NoteResource($note);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $note = Note::find($id);
        $note->user_id = $request -> input('user_id');
        $note->course_id = $request -> input('course_id');
        $note->title = $request -> input('title');
        $note->body = $request -> input('body');
        $note->file_name = $request -> input('file_name');
        $note->save();
        return new NoteResource($note);
        return response() -> json('success', 200);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $note = Note::find($id);
        $note -> delete();
        return response() -> json('success', 200);
    }
}

My Note Resource:

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class Note extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'user_id' => $this->user_id,
            'course_id' => $this->course_id,
            'title' => $this->title,
            'body' => $this->body,
            'file_name' => $this->file_name,
            'created_at' => $this->created_at->format('d/m/Y'),
            'updated_at' => $this->updated_at->diffForHumans(),
        ];
    }
}

API Routes:

<?php

use Illuminate\Http\Request;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

// Route::middleware('auth:api')->get('/user', function (Request $request) {
//     return $request->user();
// });

//Index Page Vue
Route::get('/', 'PagesControllerApi@index');

//Afficher la liste de toutes les notes
Route::get('notes', 'NotesApiController@index');

//Montre une note selon son id
Route::get('notes/{id}', 'NotesApiController@show'); 

//Enregistre la note
Route::post('notes', 'NotesApiController@store'); 

//Mise-à-jour d'une note
Route::put('notes/{id}', 'NotesApiController@update'); 

//Effacer une note
Route::delete('notes/{id}', 'NotesApiController@destroy');

APP.JS of Vue:

/**
 * First we will load all of this project's JavaScript dependencies which
 * includes Vue and other libraries. It is a great starting point when
 * building robust, powerful web applications using Vue and Laravel.
 */
require('./bootstrap');

window.Vue = require('vue');


/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */

Vue.component('notes', require('./components/notes.vue'));
Vue.component('navbar', require('./components/navbar.vue'));
Vue.component('paginate', require('vuejs-paginate'));


const app = new Vue({
    el: '#app'
});

My Note Component in Vue

<template>
<div>

    <h2 class="m-4">Notes</h2>

</div>
</template>

<script>

    export default {
        data() {
            return{
                notes: [],
                note: {
                    id: '',
                    user_id: '',
                    course_id: '',
                    title: '',
                    body: '',
                    file_name:'',
                },
                note_id: '',
                pagination: {},
                edit: false
            };
        },

        created() {
            this.fetchArticles();
        },

        methods: {
            fetchArticles(page_url) {
            let vm = this;
            page_url = page_url || '/api/notes';
            fetch(page_url)
                .then(res => res.json())
                .then(res => {
                this.articles = res.data;
        })
        .catch(err => console.log(err));
        },
        } 
    }
</script>

index.blade.php

<!DOCTYPE html>
<html lang="{{ app()->getLocale() }}">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <script>window.Laravel = { csrfToken: "{{ csrf_token() }}" }</script>

    <title>{{ config("app.name", "Laravel") }}</title>

    <!-- Scripts -->
    <script src="{{ asset('js/app.js') }}" defer></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

    <!-- Fonts -->
    <link rel="dns-prefetch" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css?family=Raleway:300,400,600" rel="stylesheet" type="text/css">

    <!-- Styles -->
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<body>
    <div id="app">

    <navbar></navbar>

       <div class="container">
           <notes>

           </notes>
       </div>
    </div>

</body>
</html>

API

Results

What the VUE Develope shows

Empty Array

Because of that I can't show any value on my page..

Thanks in advance!

  • 写回答

1条回答 默认 最新

  • dpd66100 2018-05-12 16:20
    关注

    It should be this.notes = res.data but you have this.articles = res.data;

    Then you just need to loop over the array and access properties on the object, something like this:

    <div v-for="(note, index) in notes" :key="`note-${key}`">
        <h2 v-text="note.title"></h2>
        <p v-text="note.body"></p>
        <p v-text="note.filename"></p>
    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器