我正在开发一个大型应用程序,在处理来 self 的 API 的数据并将其传递到我的子组件时遇到了很多麻烦。
情况。
我从父组件调用我的 API,并通过 prop 将数据传递到我的子组件。子组件可以很好地显示数据,但我无法在子组件的就绪函数中访问数据。
看看:https://jsfiddle.net/kmrfkynf/3/
正如您在控制台中看到的那样,在子组件就绪函数中显示数据会给我一个空对象...
ready: function(){
console.log('items from child component', this.items);
}
...但是子组件在我的重复中很好地渲染了对象。
所以问题是子组件在父组件的 API 调用完成之前渲染。完成后,它将数据同步到我的子组件,从而渲染得很好。
我尝试过的
从我的子组件中观看 Prop 。当 Prop “完成”时,我可以访问它。但这在尝试修改 prop 中的某些数据时给我带来了很多问题,因为它每次都会渲染。这不是我想要的解决方案。
问题
当子组件准备好时,如何确保 Prop 被填充?
最佳答案
问题在于 DOM 已加载并准备就绪,而 AJAX 函数仍在接收数据。因此,组件上的 ready 方法会在结果从服务器返回之前触发。
当数据从服务器返回时,你可以触发一个事件来告诉 child :
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'
})
关于javascript - 使用 Vue.js 访问子组件中的 api 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34219738/