[英]Access api data in child component on ready with Vue.js
我正在开发一个大型应用程序,我在处理来自API的数据并将其传递给我的子组件时遇到了很多麻烦。
情况。
我从父组件调用我的API,并通过prop将数据传递给我的子组件。 子组件显示数据就好了,但是我无法访问子组件中ready函数中的数据。
看看: https : //jsfiddle.net/kmrfkynf/3/
正如您在控制台中看到的那样,在子组件就绪函数中显示数据会给我一个空对象...
ready: function(){
console.log('items from child component', this.items);
}
...但是子组件在重复中呈现对象就好了。
所以问题是在父调用API调用完成之前呈现子组件。 完成后,它会将数据同步到我的子组件,因此渲染得很好。
我试过的
从我的孩子组件中看到道具。 当道具“完整”时,我可以访问它。 但是当尝试修改道具中的某些数据时,这会给我带来很多问题,因为它每次都会渲染。 这不是我想要的解决方案。
这个问题
当子组件准备好时,如何确保支撑被填充?
问题是,当AJAX函数仍在接收数据时,DOM已加载并准备就绪。 因此,组件上的ready方法在结果从服务器返回之前触发。
您可以触发一个事件来告诉孩子何时从服务器返回数据:
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'
})
正如@ Douglas.Sesar所说, item
组件的ready
方法在结果从服务器返回之前触发。
要解决这个问题,您需要添加的是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);
}
})
在组件插入之前调用该钩子。 在调用done
回调之前,不会插入组件。 当items
发生变化时,将调用done
回调(有关详细信息,请参阅watch
)。 因此,当调用ready
函数时, items
将具有正确的数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.