vue3 + typescript + axios封装(附带loading效果,...并携带跨域处理,...element-plus按需引入)

发布时间:2022-07-02 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了vue3 + typescript + axios封装(附带loading效果,...并携带跨域处理,...element-plus按需引入)脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

  简单的6步即可完成:

首先.在根目录创建vue.config.js里面配置跨域处理,

然后在src下新建service目录,在目录中新建两个ts文件,一个为request.ts 另一个为api.ts

1.对vue.config.js进行一系列配置

module.exports = {
  // 别名
  configureWebpack: {
    resolve: {
      alias: {
        views: '@/views',
        com: '@/components'
      }
    }
  },
  // 跨域请求
  devServer: {
    // oPEn: false,//
    // host: 'localhost',
    // port: 8080,
    // https: false,
    //以上的ip和端口是我们本机的;下面为需要跨域的
    Proxy: {
      //配置跨域
      '/api': {
        target: 'https://www.liulongbin.top:8888/api/PRivate/v1/', //这里后台的地址模拟的;应该填写你们真实的后台接口
        ws: true,
        changOrigin: true, //允许跨域
        pathrewrITe: {
          '^/api': '' //请求的时候使用这个api就可以
        }
      }
    }
  }
}

2.在request.ts中进行一系列配置

import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } From 'axios' //导入axios 和钩子
import { ElLoading } from 'element-plus' //导入ElLoading
import { ILoadingInstance } from 'element-plus/lib/components/loading/src/loading.type' //导入ElLoading钩子

// 初始化loading

export class Request {
  public static axiosInstance: AxiosInstance
  public static loading?: ILoadingInstance //loading实例 挂载到公共的静态属性上 方便获取

  public static init() {
    // 创建axios实例
    this.axiosInstance = axios.create({
      baseURL: '/api', //转接
      timeout: 6000
    })
    // 初始化拦截器
    this.initInterceptors()
    return axios
  }

  // 初始化拦截器
  public static initInterceptors() {
    // 设置post请求头
    this.axiosInstance.defaults.headers.post['Content-type'] =
      'application/x-www-form-urlencoded'
    /**
     * 请求拦截器
     * 每次请求前,如果存在token则在请求头中携带token
     */

    this.axiosInstance.interceptors.request.use(
      (config: AxiosRequestConfig) => {
        //  loading打开
        this.loading = ElLoading.service({
          lock: true,
          text: '正在请求数据...',
          background: 'rgb(0,0,0,0.5)'
        })

        const token = localStorage.getItem('access_token') //保存token到localStorage中
        if (token) {
          ;(config as any).headers.Authorization = 'Bearer ' + token //携带请求头
          // ;(config as any).headers.Authorization = sessionStorage.token
        }
        return config
      },
      (error: any) => {
        console.LOG(error)
      }
    )

    // 响应拦截器
    this.axiosInstance.interceptors.response.use(
      // 请求成功
      (response: AxiosResponse) => {
        this.loading?.close() //将loading移除

        if (response.status === 200) {
          // return Promise.resolve(response.data);
          return response
        } else {
          Request.errorHandle(response)
          // return Promise.reject(response.data);
          return response
        }
      },
      // 请求失败
      (error: any) => {
        const { response } = error
        if (response) {
          // 请求已发出,但是不在2xx的范围
          Request.errorHandle(response)
          return Promise.reject(response.data)
        } else {
          // 处理断网的情况
          // eg:请求超时或断网时,更新state的network状态
          // network状态在app.vue中控制着一个全局的断网提示组件的显示隐藏
          // 关于断网组件中的刷新重新获取数据,会在断网组件中说明
          // message.warn('网络连接异常,请稍后再试!')
          console.log('网络连接异常,请稍后再试!')
        }
      }
    )
  }

  /**
   * http握手错误
   * @param res 响应回调,根据不同响应进行不同操作
   */
  private static errorHandle(res: any) {
    // 状态码判断
    switch (res.status) {
      case 401:
        break
      case 403:
        break
      case 404:
        // message.warn('请求的资不存在'),
        console.log('请求的资源不存在')
        break
      default:
        // message.warn('连接错误')
        console.log('连接错误')
    }
  }
}

3.在api.ts中对接口进一步管理

import { Request } from './request'//导入请求拦截器request

export function getUserlist(parameter: any) {//导出方法
  return Request.axiosInstance({
    url: '/login',
    method: 'post',
    data: parameter
  })
}

4.在main.ts中导入请求拦截器 、element-plus

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import Store from './store'

// 导入请求拦截器
import { Request } from '@/service/request'
import VueAxios from 'vue-axios'

//element-plus 按需引入
import 'element-plus/dist/index.css' //局部样式
import { components } from './plugins/element-plus' //局部js

const app = createApp(App)
for (const cpn of components) {
  app.COMponent(cpn.name, cpn)
}

app.use(store).use(router).use(VueAxios, Request.init()).mount('#app')

5.在src下新建plugs目录,里新建element-plus.ts 然后配置下面模块

import {
  ElButton,
  ElTable,
  ElAlert,
  ElAside,
  ElAutocomplete,
  ElAvatar,
  ElBacktop,
  ElBadge,
  ElLink,
  ElForm,
  ElFormItem
} from 'element-plus'
export const components = [
  ElButton,
  ElTable,
  ElAlert,
  ElAside,
  ElAutocomplete,
  ElAvatar,
  ElBacktop,
  ElBadge,
  ElLink,
  ElForm,
  ElFormItem
]

6.在页面按需导入需要用到的api接口

<template>
  <div class="home">
    <div>ss</div>
    <img alt="Vue logo" src="../assets/logo.png" />
    <HelloWorld msg="Welcome to Your Vue.js + TypeScript App" />
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue'

import HelloWorld from '@/components/HelloWorld.vue' // @ is an alias to /src
import { getUserlist } from '@/service/api' //接口
export default defineComponent({
  name: 'Home',
  components: {
    //挂载组件
    HelloWorld
  },
  SETUP() {
    //定义数据 和方法
    getUserlist({ username: 'admin', password: '123456' }).then((res) => {
      console.log(res)
    })

    return {}
  }
})
</script>

脚本宝典总结

以上是脚本宝典为你收集整理的vue3 + typescript + axios封装(附带loading效果,...并携带跨域处理,...element-plus按需引入)全部内容,希望文章能够帮你解决vue3 + typescript + axios封装(附带loading效果,...并携带跨域处理,...element-plus按需引入)所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。