Access api data in child component on ready with Vue.js
The problem is that the DOM is loaded and ready while the AJAX function is still receiving the data. So the ready method on the component fires before the results come back from the server.
You could fire an event to tell the child when the data is back from the server:
var item = Vue.extend({ props: ['items'], data:function(){return{items:[]}}, template: '<div v-for="item in items">{{ item }}</div>', ready: function(){ this.$on('datahere', function(){ alert(this.items[0].id); //console.log('datahere items', this.items); }) //console.log('items from child component', this.items); }})Vue.component('item', item);var items = Vue.extend({ ready: function(){ this.init(); }, data: function(){ return { items: {} } }, methods:{ init: function(){ this.getItems(); }, getItems: function(){ this.$http.get('https://api.github.com/users/mralexgray/repos') .success(function(data){ this.$set('items', data); this.$nextTick(function(){ this.$broadcast('datahere', data); }); console.log('items from parent components: ', this.$get('items')); }) } }, template: '<div class="test"><item :items.sync="items"></item></test>', components: {'item': item}})Vue.component('items', items);var app = new Vue({ el: '#app'})
As @Douglas.Sesar said, the ready
method on the item
component fires before the results come back from the server.
To fix that, all you need to add is the activate hook
:
var item = Vue.extend({ activate: function(done) { var unwatch = this.$watch('items', function() { unwatch(); // teardown the watcher done(); // ready to insert the component }); }, props: ['items'], template: '<div v-for="item in items">{{ item }}</div>', ready: function(){ console.log('items from child component', this.items); }})
That hook is called before component insertion. The component will not be inserted until the done
callback is called. The done
callback is called when the items
changed (see watch
for details). Hence, the items
will have the correct data when the ready
function is called.