在vue2
中會習慣性的把axios
掛載到全局,以方便在各個組件或頁面中使用this.$http
請求接口。但是在vue3
中取消了Vue.prototype
,在全局掛載方法和屬性時,需要使用官方提供的globalProperties
API。
一、全局掛載
- 在
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
中使用getCurrentInstance
API獲取全局對象:
<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()
看到其中有很多全局對象,如:$route
、$router
、$store
。如果全局使用了ElementUI
后,還可以拿到$message
、$dialog
等等。
《Vue3學習與實戰》系列
- Vue3學習與實戰 · 組件通信
- Vue3學習與實戰 · 全局掛載使用Axios(本文)
- Vue3學習與實戰 · 配置使用vue-router路由
- Vue3學習與實戰 · Vuex狀態管理
- vue3 + vite實現異步組件和路由懶加載
- Vite+Vue3+Vant快速構建項目
歡迎訪問:天問博客