【发布时间】:2016-12-13 15:32:58
【问题描述】:
组件安装后如何获取数据?
我启动我的 vue 实例,然后加载组件,组件模板加载正常,但 mount 中的函数调用从未运行,因此 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');
}
});
【问题讨论】:
-
您正在向组件传递 3 个参数,但
Vue.component只需要 2 个参数,即 id 和定义:vuejs.org/v2/api/#Vue-component -
@craig_h 啊,我明白了,我正在遵循 Laravel 加载组件 github.com/laravel/laravel/blob/master/resources/assets/js/… 的约定,就像这里一样。那么如何调用mounted在组件上呢?
-
用 require 加载你的组件很好,但是你的视图模型(基本上你作为第三个参数添加的所有代码)应该在
Homepage.vue中。看看single file components 看看它们是如何工作的。
标签: javascript vue.js vuejs2