[英]Class import into Vue component
I want to make separate class for axios requests, which works like "service" 我想为axios请求创建单独的类,其工作方式类似于“服务”
Vue component: 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>
And the service is the following: 服务如下:
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;
}
}
As I can see in my console, I get the data from axios xhr request, but then they are not passed to the Vue Component, because I get empty object in the string console.log("This are users " + this.users); 正如我在控制台中看到的那样,我是从axios xhr请求中获取数据的,但是这些数据没有传递给Vue组件,因为我在字符串console.log(“ This are users” + this.users)中得到了空对象。 ;
How to import COnnectionService properly and then use it in Vue Component? 如何正确导入COnnectionService,然后在Vue Component中使用它?
Modify the next in your 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)
});
}
Like getSingleInstance returns an object I recommend declaring user like this: user: Object
or user: {}
instead user: []
就像getSingleInstance返回一个对象一样,我建议这样声明用户:
user: Object
或user: {}
而不是user: []
It seems that you have to use promises because .get
is an async function. 似乎您必须使用Promise,因为
.get
是一个异步函数。 To install Q promises package see: Q 要安装Q promises软件包,请参阅: Q
How to use in your example: 在您的示例中如何使用:
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
}
}
As you can see I have changed the arrow syntax ( =>
) because I clarify more like this. 如您所见,我更改了箭头语法(
=>
),因为我对此进行了更清晰的说明。
I can not test it and I'm not an expert (I just try to help) but I think it should work. 我无法测试它,而且我不是专家(我只是想提供帮助),但我认为它应该可以工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.