vue3全局封装axios.js

vue3】与vue2的差异

因为vue的混合api setup上不能使用this,因此混合模式下直接使用axios.get报错,

解决方案有3

一、引入api

定义axios.js封装

import axios from ‘axios’

import store from ‘@/store’

import router from ‘@/router’

import { ElMessage, ElLoading } from ‘element-plus’

const instance = axios.create({

    headers: {

        ‘Content-Type’: ‘application/json’,

    },

})

//加载动画

let loading = null

instance.interceptors.request.use(

    function (config) {

        const baseUrl = import.meta.env.MODE == ‘development’ ? ‘http://houdunren.test/api’ : ‘/’

        config.baseURL = baseUrl

        //携带令牌

        const token = window.localStorage.getItem(‘token’)

        if (token) config.headers.Authorization = `Bearer ${token}`

        //加载动画

        loading = ElLoading.service({

            lock: true,

            text: ‘加载中…’,

            spinner: ‘el-icon-loading’,

            background: ‘rgba(255, 255, 255, 0)’,

        })

        return config

    },

    function (error) {

        return Promise.reject(error)

    }

)

instance.interceptors.response.use(

    function (response) {

        loading.close()

        const { data } = response

        if (data.message) {

            ElMessage.success({

                message: data.message,

                type: ‘success’,

            })

        }

        return data

    },

    function (error) {

        loading.close()

        const { status, data } = error.response

        switch (status) {

            case 422:

                //表单验证失败

                store.commit(‘error/set’, data.errors)

                break

            case 401:

                store.commit(‘user/logout’)

                router.push(‘/login’)

                break

        }

        return Promise.reject(error)

    }

)

export default instance

然后在组件中调用axios

<script>

import api from ‘@/plugins/api’

export default{

    setup(){

        const content=api.get(‘content’)

    }

}

</script>

方式二:代理模式,与引入api操作一样,需要引入,代码量差不多不过多介绍

main.js

const app = createApp(App);

import axios from “axios”;

app.config.globalProperties.$axios = axios;

组件中使用

import { getCurrentInstance } from “vue”;

  setup() {

let { proxy } = getCurrentInstance();

proxy.axios.get(‘XX’)

}

方式三:【推荐】插件+全局绑定

vue-axios插件加window全局绑定

yarn add global vue-axios

main.js

import {createApp} from ‘vue’

import App from ‘./App.vue’

import ‘./assets/tailwind.css’

import ‘./assets/app.scss’

import axios from ‘@/plugins/axios’

import VueAxios from ‘vue-axios’

const app = createApp(App)

app.use(VueAxios, axios).mount(‘#app’)

注意在:@/plugins/axios中需要将axios实例挂载到window

window.axios = instance

接下来,奇迹发生了

setup模式下可以直接使用axios.get(‘XXX’)发送网络请求。

源码分析:

实际是采用了vue3provide inject 实现

vue-axios库中的index.js

 app.provide(‘axios’, app.config.globalProperties.axios) // provide ‘axios’

      app.provide(‘$http’, app.config.globalProperties.$http) // provide ‘$http’

 

if (typeof exports == “object”) {

  module.exports = plugin;

} else if (typeof define == “function” && define.amd) {

  define([], function () { return plugin });

} else if (window.Vue && window.axios && window.Vue.use) { // Vue.use is only available in VueJS 2.0

  Vue.use(plugin, window.axios);

}

© 版权声明
THE END
喜欢就支持一下吧
点赞8
分享
评论 抢沙发
袁浩的头像孙先森资源|专注优质网络资源教程分享孙先森资源教程

昵称

取消
昵称表情代码图片