Mar*_*tra 7 javascript api components vue.js
我正在开发一个大型应用程序,我在处理来自API的数据并将其传递给我的子组件时遇到了很多麻烦.
情况.
我从父组件调用我的API,并通过prop将数据传递给我的子组件.子组件显示数据就好了,但是我无法访问子组件中ready函数中的数据.
看看:https://jsfiddle.net/kmrfkynf/3/
正如您在控制台中看到的那样,在子组件就绪函数中显示数据会给我一个空对象...
ready: function(){
console.log('items from child component', this.items);
}
Run Code Online (Sandbox Code Playgroud)
...但是子组件在重复中呈现对象就好了.
所以问题是在父调用API调用完成之前呈现子组件.完成后,它会将数据同步到我的子组件,因此渲染得很好.
我试过的
从我的孩子组件中看到道具.当道具"完整"时,我可以访问它.但是当尝试修改道具中的某些数据时,这会给我带来很多问题,因为它每次都会渲染.这不是我想要的解决方案.
这个问题
当子组件准备好时,如何确保支撑被填充?
问题是 DOM 已加载并准备就绪,而 AJAX 函数仍在接收数据。因此,组件上的 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'
})
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6870 次 |
最近记录: |