[英]Class import into Vue component
我想為axios請求創建單獨的類,其工作方式類似於“服務”
Vue組件:
<template>
<div v-for="user in users">
{{ user.firstname }} - {{ user.lastname }} - {{ user.middlename }}
</div>
</template>
<script>
import ConnectionService from './ConnectionService';
const connectionService = new ConnectionService();
export default {
mounted() {
console.log('Component is mounted');
},
created() {
this.users = connectionService.getSingleInstance('http://laravelapi/user');
console.log("This are users " + this.users);
},
data() {
return {
users: [],
}
}
}
</script>
服務如下:
export default class ConnectionService {
getSingleInstance(path) {
console.log('This is path ' + path);
let axios_data = {};
axios.get(path).then(response => axios_data = response.data.result);
console.log('This is data ' + axios_data);
console.log(axios_data);
return axios_data;
}
}
正如我在控制台中看到的那樣,我是從axios xhr請求中獲取數據的,但是這些數據沒有傳遞給Vue組件,因為我在字符串console.log(“ This are users” + this.users)中得到了空對象。 ;
如何正確導入COnnectionService,然后在Vue Component中使用它?
修改vue組件中的下一個:
created() {
connectionService.getSingleInstance('http://laravelapi/user')
.then(function(response){
this.users = response
console.log("This are users " + this.users);
})
.catch(function(error){
console.log(error)
});
}
就像getSingleInstance返回一個對象一樣,我建議這樣聲明用戶: user: Object
或user: {}
而不是user: []
似乎您必須使用Promise,因為.get
是一個異步函數。 要安裝Q promises軟件包,請參閱: Q
在您的示例中如何使用:
import Q from 'q'
export default class ConnectionService {
getSingleInstance(path) {
var deferred = Q.defer()
console.log('This is path ' + path);
axios.get(path)
.then(
function(response) {
deferred.resolve(response.data.result)
},
function(error){
deferred.reject(error)
})
return deferred.promise
}
}
如您所見,我更改了箭頭語法( =>
),因為我對此進行了更清晰的說明。
我無法測試它,而且我不是專家(我只是想提供幫助),但我認為它應該可以工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.