vue-cli配置axios,并基于axios进行后台请求函数封装

文章https://www.cnblogs.com/XHappyness/p/7677153.html已经对axios配置进行了说明,后台请求时可直接this.$axios直接进行。这里的缺点是后端请求会散乱在各个组件中,导致复用和维护艰难。

升级:将请求封装在一个文件中并加上类型声明

步骤:

1. npm install axios --save

2. src/common下建server.ts 内容如下

/**
 * 后台请求设置
 */
import axios from 'axios'
// import {Notification} from 'element-ui'
import { serverUrl } from './configByEnv.js'

axios.defaults.withCredentials = true;
axios.defaults.baseURL = serverUrl;

axios.interceptors.request.use(function (config) {
    return config;
}, function (error) {
    return Promise.reject(error)
})

axios.interceptors.response.use(function (response) {
    return response.data;
}, function (error) {
    if (error.response.status === 401) {
        alert(401);
        // Notification({
        //   title: '权限无效',
        //   message: '您的用户信息已经失效, 请重新登录',
        //   type: 'warning',
        //   offset: 48
        // });
        // window.location.href = '/#/login'
    } else {
        alert('请求错误');
        // Notification({
        //   title: '请求错误',
        //   message: `${error.response.status} \n ${error.config.url}`,
        //   type: 'error',
        //   offset: 48,
        // })
    }
    return Promise.reject(error)
})

/**
 * 后台请求函数
 */
class Server implements Server.IServer {
    // 所有请求函数写在这里
    login_async(curSlnId: Server.loginUser): Promise<string[]> {
        return axios.get(`/login/${curSlnId}`).then((res: any) => res)
    }
}

export default new Server()    
View Code

3. src/types下建server.d.ts,加入server的类型声明

declare namespace Server {
    // 本文件自己用的不用加export
    export interface loginUser {
        name: string,
        psd: string
    }
    export interface IServer {
        login_async(loginUser: loginUser): Promise<string[]>;
    }
}
View Code

4. Vue原型添加$server

(1) main.ts中添加

import server from './common/server';
Vue.prototype.$server = server;

 (2)src/types下建vue.d.ts,也就是声明 Vue 插件补充的类型(https://minikiller.github.io/v2/guide/typescript.html#%E5%A3%B0%E6%98%8E-Vue-%E6%8F%92%E4%BB%B6%E8%A1%A5%E5%85%85%E7%9A%84%E7%B1%BB%E5%9E%8B),内容如下:

/* 补充Vue类型声明 */
import Vue from 'vue'  // 注意要用这一步
declare module 'vue/types/vue' {
    interface Vue {
        $server: Server.IServer;
    }
}
View Code

5. 可以在任何组件中用this.$server使用封装的请求方法了,还有有类型检查和类型提示。

  

猜你喜欢

转载自www.cnblogs.com/XHappyness/p/9993878.html
今日推荐