why items are not loading in blog.vue?

122 Views Asked by At

I am loading template from blog.vue in app.js, but with this it displays only header row of table not table rows as ajax call is not made.

If i comment require('./bootstrap');, it does not display table header, ajax is called but no data is displayed in table rows.

1. blog.vue file

<template>
<div class="table-responsive">
  <table class="table table-borderless">
    <tr>
      <th>Title</th>
      <th>Description</th>
    </tr>
    <tr v-for="item in items">
      <td>@{{ item.title }}</td>
      <td>@{{ item.description }}</td>

    </tr>
  </table>
</div>
</template>

<script>
    export default {
        mounted() {
            console.log('Component ready.')
        }
    }
</script>

2. app.js file

require('./bootstrap');

Vue.component('list-blog', require('./components/blog.vue'));

new Vue({
  el :'#manage-vue',
  data :{
    items: [],
    newItem : {'title':'','description':''},
    fillItem : {'title':'','description':'','id':''}
  },

  ready: function() {
    this.getVueItems();
  },
  methods: {
    getVueItems: function() {
      this.$http.get('/vueitems?page='+page).then((response) => {
        this.$set('items', response.data.data.data);
        this.$set('pagination', response.data.pagination);
      });
    },
  }
});

3. bootstrap.js

window._ = require('lodash');

window.$ = window.jQuery = require('jquery');
require('bootstrap-sass');


window.Vue = require('vue');
require('vue-resource');

Vue.http.interceptors.push((request, next) => {
    request.headers.set('X-CSRF-TOKEN', Laravel.csrfToken);

    next();
});

Can you please tell me where am i wrong in this ? i am using laravel-elixir here.

1

There are 1 best solutions below

7
On

I think this should be only response.data.data

// this.$set('items', response.data.data.data);
// to
this.$set('items', response.data.data);

You could even simplify this

this.$http.get('/vueitems?page='+page).then((response) => {
    this.items = response.data.data;
    this.pagination = response.data.pagination;
}.bind(this)); // important bind(this)

It seems like you are returning a paginated object. Therefore the third data is false - isn't it? Also you would usually pass the items to the component as property. Simply define the prop at your blog.vue

<script>
export default {
    props: ['items'],
    mounted() {
        console.log('Component ready.')
    }
}
</script>

And then pass it whereever you use it

<list-blog :items="items"></list-blog>

I highly recommend to use Chrome and the Vue devtools https://github.com/vuejs/vue-devtools - these will help you to follow and undestand the data bindings

Another smaller thing is that you shouldn't bind the pagination object AND the items seperatly. The pagination object contains the items. If you don't want o use "pagination.data" in your templates simply use a computed property instead of creating two sources of truth.