vue2、vue3的全局挂载使用axios

在vue2中会习惯性的把axios挂载到全局,以方便在各个组件或页面中使用this.$http请求接口。但是在vue3中取消了Vue.prototype,在全局挂载方法和属性时,需要使用官方提供的globalPropertiesAPI。

一、全局挂载

在vue2项目中,入口文件main.js配置Vue.prototype挂载全局方法对象:

import Vue from 'vue'
import router from '@/router'
import store from '@vuex'
import Axios from 'axios'
import Utils from '@/tool/utils'
import App from './App.vue'

// ...

/* 挂载全局对象 start */
Vue.prototype.$http = Axios;
Vue.prototype.$utils = Utils;
/* 挂载全局对象 end */

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

在vue3项目中,入口文件main.js配置globalProperties挂载全局方法对象:

import { createApp } from 'vue'
import router from './router'
import store from './store'
import Axios from 'axios'
import Utils from '@/tool/utils'
import App from './App.vue'

// ...

const app = createApp(App)

/* 挂载全局对象 start */
app.config.globalProperties.$http = Axios
app.config.globalProperties.$utils = Utils
/* 挂载全局对象 end */

app.use(router).use(store);
app.mount('#app')

二、全局使用

在vue2中使用this.$http:

<script>
  export default {
    data() {
      return {
        list: []
      }
    },
    mounted() {
      this.getList()
    },
    methods: {
      getList() {
        this.$http({
          url: '/api/v1/posts/list'
        }).then(res=>{
          let { data } = res.data
          this.list = data
        })
      },
    },
  }
</script>

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

<template>
  <div class="box"></div>
</template>
<script>
  import { ref, reactive, getCurrentInstance } from 'vue'
  export default {
    setup(props, cxt) {
      // 方法一 start
      const currentInstance = getCurrentInstance()
      const { $http, $message, $route } = currentInstance.appContext.config.globalProperties
      
      function getList() {
        $http({
          url: '/api/v1/posts/list'
        }).then(res=>{
          let { data } = res.data
          console.log(data)
        })
      }
      // 方法一 end

      // 方法二 start
      const { proxy } = getCurrentInstance()
      
      function getData() {
        proxy.$http({
          url: '/api/v1/posts/list'
        }).then(res=>{
          let { data } = res.data
          console.log(data)
        })
      }
      // 方法二 end

    }  
  }
</script>

方法一:通过getCurrentInstance方法获取当前实例,再根据当前实例找到全局实例对象appContext,进而拿到全局实例的config.globalProperties。
方法二:通过getCurrentInstance方法获取上下文,这里的proxy就相当于this。
提示: 可以通过打印getCurrentInstance()看到其中有很多全局对象,如:r o u t e 、 route、route、router、s t o r e 。 如 果 全 局 使 用 了 E l e m e n t U I 后 , 还 可 以 拿 到 store。如果全局使用了ElementUI后,还可以拿到store。如果全局使用了ElementUI后,还可以拿到message、$dialog等等。

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值