Search code examples
vuejs2axioslaravel-5.7

Getting data from Laravel Api to Vue Page


I'm a beginner in vue.js and I'm trying to get an api result and show it to my vue page. my Api is built with Laravel 5.7. I've just installed Vue axios package to work with http.

Here is my code:

TaskController

 public function index()
 {
    return response(Task::all()->jsonSerialize(), Response::HTTP_OK);
 }

App.vue

<template>
<div class="app-component">
    <table class="table">
        <thead>
            <tr>
                <th>ID</th>
                <th>Task Title</th>
                <th>Priority</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
            <task-component v-for="task in tasks" :key="task.id" :task="task"></task-component>
           <tr>
               <td><input type="text" id="task" class="form-control"></td>
               <td>
                   <select id="select" class="form-control">
                       <option>Low</option>
                       <option>Medium</option>
                       <option>High</option>
                   </select>
                </td>
                <td><button class="btn btn-primary">Add</button></td>
            </tr>
        </tbody>
    </table>
</div>
</template>

<script>
import TaskComponent from './Task.vue';
export default{
    data(){
        return{
                tasks: [],
        }
    },

    methods: {
        getTasks(){
            window.axios.get('/api/tasks').then(({data})=>{
                data.forEach(task =>{
                this.tasks.push(task)
            });
          });
        },
        created(){
            this.getTasks();
        }
    },
    components:{TaskComponent}
}
</script>

Task Page

<template>
     <tr>
        <td>{{ task.id }}</td>
        <td>{{ task.title }}</td>
        <td>{{ task.priority }}</td>
        <td><button class="btn btn-danger">Remove</button></td>
    </tr>
</template>
<script>
export default{
    data(){
        return{
        }
    },
    props: ['task']
}   

</script>

I got no errors but no result appeared to my vue although the controller returns json data correctly


Solution

  • the created() hook should not be in methods:

    export default {
       methods: {},
       created() {}
    }