vue 接口封装问题

说明: get和post方式是封装在axios.js里面的.目录里common.js同级

clipboard.png

//common.js文件

import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
export default{
    login:function(){
        this.axios.get("", {})
        .then(res => {
            let { msg, code, data } = res.data;
            if (code !== 1) {
                this.$message({
                    message: msg,
                    type: "error"
                });
            } else {
                console.log(res);
            }
        })
        .catch(function(error) {
            console.log(error);
        });
    }
}

//InstitutionSetup.vue 文件

mounted() {
    this.common.login()
}

clipboard.png

阅读 3.5k
4 个回答
import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
export default{
    login:function(){
        axios.get("", {})
        .then(res => {
            let { msg, code, data } = res.data;
            if (code !== 1) {
                this.$message({
                    message: msg,
                    type: "error"
                });
            } else {
                console.log(res);
            }
        })
        .catch(function(error) {
            console.log(error);
        });
    }
}

Vue.prototype.$axios = axios

引入axios并没有挂载到Vue上面,你可以在export default之前加上Vue.prototype.axios = axios之后下面的代码就可以用了

this问题
你应该是 Vue.prototype.common = common

this.login() 这个login里的thisvue实例
this.common.login() 这个login里的thiscommon 并不是vue实例

this.common.login.call(this)

可以这样理解

let common = {
  name:'common',
  login:function(){
    console.log(this.name);
  }
}

let vue = {
  name:'vue',
  common,
}

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