【问题标题】:Class import into Vue component类导入 Vue 组件
【发布时间】:2017-10-11 21:01:40
【问题描述】:

我想为 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中使用?

【问题讨论】:

    标签: javascript vuejs2


    【解决方案1】:

    在你的 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: Objectuser: {} 而不是 user: []

    您似乎必须使用 Promise,因为 .get 是一个异步函数。要安装 Q Promise 包,请参阅: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
        }
    }
    

    如您所见,我更改了箭头语法 (=&gt;),因为我更喜欢这样澄清。

    我无法测试它,我也不是专家(我只是想帮忙),但我认为它应该可以工作。

    【讨论】:

    • 尝试执行此操作,但出现以下错误:app.js:34877 [Vue 警告]:创建钩子时出错:“TypeError: connectionService.getSingleInstance(...).then 不是函数”
    • @ILya 我编辑了我的答案(我不知道它是否会起作用)但无论如何我认为这是由于异步功能造成的问题,您可以查找有关它的信息来解决它。
    猜你喜欢
    • 2017-01-27
    • 2018-01-16
    • 1970-01-01
    • 2019-04-23
    • 1970-01-01
    • 2017-05-18
    • 2020-06-18
    • 2019-02-03
    • 1970-01-01
    相关资源
    最近更新 更多