一旦組件安裝完成後如何獲取數據?
我開始我的vue實例,然後加載組件,組件模板加載正常,但掛載的函數調用永遠不會運行,因此stats對象保持爲空,從而導致需要數據的組件/模板中出現錯誤。在加載VueJs 2組件後運行功能
那麼如何在組件加載上運行某個函數呢?
對於它的價值......我想調用的函數將全部生成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和定義:https://vuejs.org/v2/api/#Vue-component –
@craig_h ahh我看到,我正在按照組件https://github.com/laravel/laravel/blob/master/resources/assets/js/app.js中的Laravel慣例加載。那麼我怎麼會在組件上調用? – twigg
用你的組件加載require是可以的,但是你的視圖模型(基本上你添加的所有代碼作爲第三個參數)應該在'Homepage.vue'中。看看[單個文件組件](https://vuejs.org/v2/guide/single-file-components.html),看看它們是如何工作的。 –