如何在安装组件后获取数据?
我启动我的vue实例,然后加载组件,组件模板加载正常,但挂载的函数调用永远不会运行,因此stats对象保持为空,反过来导致组件/模板中的错误需要数据。
那么如何在组件加载上运行某个函数呢?
它的价值......我想要调用的函数都会发出REST请求,但每个组件都会运行不同的请求。
Vue.component('homepage', require('./components/Homepage.vue'), {
props: ["stats"],
mounted: function() {
this.fetchEvents();
console.log('afterwards');
},
data: {
loading: true,
stats: {}
},
methods: {
fetchEvents: function() {
this.$http.get('home/data').then(function(response) {
this.stats = response.body;
this.loading = false;
}, function(error) {
console.log(error);
});
}
}
});
const vue = new Vue({
el: '#main',
mounted: function() {
console.log('main mounted');
}
});
答案 0 :(得分:1)
通过将所有初始化内容放入mounted
,您已经做得很好。您的组件未刷新的原因可能是由于this
的绑定,如下所述:
在fetchEvents
函数中,您的$http
成功处理程序会提供您尝试分配给this.stats
的响应。但它失败了,因为this
指向匿名函数作用域而不指向Vue组件。
要解决此问题,您可以使用箭头功能,如下所示:
fetchEvents: function() {
this.$http.get('home/data').then(response => {
this.stats = response.body;
this.loading = false;
}, error => {
console.log(error);
});
}
箭头函数不会在其中创建自己的范围或this
。如果您在箭头函数中使用this
,如上所示,它仍然指向Vue组件,因此您的组件将更新其数据。
注意:即使错误处理程序需要使用箭头功能,因此您可以使用this
(Vue组件)进行任何错误记录。