Vue api接口组件问题

问题描述

目前写的代码中,在common.js中.已经.then()一次起了.为什么在vue组件中.还需要再.then()一次呢.有什么办法可以直接使用this.common.Login()就能得出想要的res的数据呢?

相关代码

common.js

Login: () => {
    return axios.get("", {})
    .then(res => {
        let { msg, code, data } = res.data;
        if (code !== 1) {
            Message({
                message: msg,
                type: "error"
            });
        } else {
            return res
            console.log(res);
        }
    })
    .catch(function(error) {
        console.log(error);
    });
}

demo.vue

    methods:{
        getList(){
            this.common.Login()
            .then( res =>{
                this.Role = res.data.data
            })
        }
    },

继续问题

如果在demo.vue组件中不进行

.then( res=> {
    this.Role = res.data.data
})

直接如下使用

getList(){
    this.common.Login()
}

的情况下.拿到的数据如下图:
多了一层Promise,请问如何解决呢?

clipboard.png

你期待的结果是什么?实际看到的错误信息又是什么?

common.js把接口方法都写死.在demo.vue组件中.直接this.common.Login()就能拿到数据.无需再.then()一下.

阅读 2.1k
1 个回答

this.Role的赋值 写在Loginthen里面
然后this.common.Login.call(this)调用
这样封装 Login达不到公用了 就不纯粹了

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题