Vue3全局掛載使用Axios學(xué)習(xí)實戰(zhàn)
引言
在vue2中會習(xí)慣性的把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方法獲取當(dāng)前實例,再根據(jù)當(dāng)前實例找到全局實例對象appContext,進(jìn)而拿到全局實例的config.globalProperties。 - 方法二:通過
getCurrentInstance方法獲取上下文,這里的proxy就相當(dāng)于this。
提示: 可以通過打印getCurrentInstance()看到其中有很多全局對象,如:$route、$router、$store。如果全局使用了ElementUI后,還可以拿到$message、$dialog等等。
以上就是Vue3全局掛載使用Axios學(xué)習(xí)實戰(zhàn)的詳細(xì)內(nèi)容,更多關(guān)于Vue3全局掛載使用Axios的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Vue 打包的靜態(tài)文件不能直接運(yùn)行的原因及解決辦法
這篇文章主要介紹了Vue 打包的靜態(tài)文件不能直接運(yùn)行的原因及解決辦法,幫助大家更好的理解和學(xué)習(xí)vue框架,感興趣的朋友可以了解下2020-11-11
vant-ui AddressEdit地址編輯和van-area的用法說明
這篇文章主要介紹了vant-ui AddressEdit地址編輯和van-area的用法說明,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-11-11

