douju1865
2018-05-12 15:59
浏览 179
已采纳

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>
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题