Vue全局挂载axios


前言

在vue开发过程中我们有时会把需要的一些模块挂载的全局,以便在各个组件或页面中使用。vue2与vue3中全局挂载是有一些不同的。


一、全局挂载

示例:pandas 是基于NumPy 的一种工具,该工具是为了解决数据分析任务而创建的。

  • vue2中挂载全局 

在vue2项目中,在入口文件main.js中通过Vue.prototype挂载全局方法对象。 

import Vue from 'vue'
import Axios from 'axios
import utils from '@/utils'
import qs from 'qs'
...

//挂载全局对象
Vue.prototype.$http = Axios;
Vue.prototype.$qs = qs
....
  • vue3中挂载全局 

 vue3中取消了Vue.prototype,需要使用官方提供的globalPropertiesAPI在全局挂载方法和属性。

import { createApp } from 'vue'
import App from './App.vue'
import router from './router/index'
import axios from './utils/axios'
import qs from 'qs'

const app = createApp(App)
//全局挂载
app.config.globalProperties.$axios = axios;
app.config.globalProperties.$qs = qs;

...

二、使用全局

  • 在vue2中使用

 vue2中使用this.$http , this.$qs

<script>
  export default {
    data() {
      return {
        dataList: []
      }
    },
    mounted() {
      this.getList()
    },
    methods: {
      getList() {
        this.$http({
          url: 'url地址'
        }).then(res=>{
          let { data } = res.data
          this.dataList = data
        })
      },
    },
  }
</script>
  • 在vue3中 使用

在vue3的setup中使用getCurrentInstanceAPI获取全局对象

//方法一
<script>
    import {useRouter} from 'vue-router';
    import {toRefs,getCurrentInstance} from 'vue';
    export default{
        setup(){
            const router = useRouter();
            const {proxy} = getCurrentInstance();
            const submit = () =>{
                proxy.$axios.post('/adminUser/login',{
                     userName:state.ruleForm.username || '',
                     passwordMd5:md5(state.ruleForm.password)
                 }).then(res=>{
                     console.log(res)
                 })
            }
            return{
                submit
            }
        }
        mounted(){
            this.submit()
        }
    }
</script>

.....
//方法二:
...
setup(){
    const currentInstance = getCurrentInstance()
    const {$axios,$route} = currentInstance.appContext.config.globalProperties
    function submit(){
        $axios.post('/adminUser/login',{
              userName:state.ruleForm.username || '',
              passwordMd5:md5(state.ruleForm.password)
        }).then(res=>{
               console.log(res)
       })
    }
}

 通过getCurrentInstance()可以得到许多的全局对象。


总结

vue2中通过Vue.prototype来挂载全局对象,然后通过this.$XXX来获取全局对象。

vue3中通过app.config.globalProperties.$xxx = xxx来挂载全局对象,然后有两种方法来获取:

  • 通过getCurrentInstance()方法获取上下文,这里的proxy就相当于this。例如:proxy.$axios
  • 通过getCurrentInstance()方法获取当前实例,在根据当前实例找到全局实例对象appContext,进而拿到全局实例的config.galbalProperties。 

猜你喜欢

转载自blog.csdn.net/weixin_42464106/article/details/125674988