安装组件后如何获取数据?
我启动我的vue实例,然后加载组件,组件模板加载得很好,但是mounted中的函数调用永远不会运行,因此统计对象保持为空,进而导致需要的组件/模板中的错误数据。
那么如何在组件加载时运行某个函数呢?
无论其值(value)如何......我想要调用的函数都会发出 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');
}
});
最佳答案
通过将所有初始化内容放入 mounted
中,您已经做得很好了。您的组件不刷新的原因可能是由于 this
的绑定(bind),如下所述:
在您的 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 组件,因此您的组件将更新其数据。
注意:即使是错误处理程序也需要使用箭头函数,以便您可以使用(Vue 组件的)this
来记录任何错误。
关于javascript - 加载后在 VueJs 2 组件中运行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41124860/