Vue3全局掛載使用Axios學(xué)習(xí)實(shí)戰(zhàn)
引言
在vue2
中會(huì)習(xí)慣性的把axios
掛載到全局,以方便在各個(gè)組件或頁(yè)面中使用this.$http
請(qǐng)求接口。但是在vue3
中取消了Vue.prototype
,在全局掛載方法和屬性時(shí),需要使用官方提供的globalProperties
API。
一、全局掛載
- 在
vue2
項(xiàng)目中,入口文件main.js
配置Vue.prototype
掛載全局方法對(duì)象:
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' // ... /* 掛載全局對(duì)象 start */ Vue.prototype.$http = Axios; Vue.prototype.$utils = Utils; /* 掛載全局對(duì)象 end */ new Vue({ router, store, render: h => h(App) }).$mount('#app')
- 在
vue3
項(xiàng)目中,入口文件main.js
配置globalProperties
掛載全局方法對(duì)象:
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) /* 掛載全局對(duì)象 start */ app.config.globalProperties.$http = Axios app.config.globalProperties.$utils = Utils /* 掛載全局對(duì)象 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獲取全局對(duì)象:
<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>
- 方法一:通過(guò)
getCurrentInstance
方法獲取當(dāng)前實(shí)例,再根據(jù)當(dāng)前實(shí)例找到全局實(shí)例對(duì)象appContext
,進(jìn)而拿到全局實(shí)例的config.globalProperties
。 - 方法二:通過(guò)
getCurrentInstance
方法獲取上下文,這里的proxy
就相當(dāng)于this
。
提示: 可以通過(guò)打印getCurrentInstance()
看到其中有很多全局對(duì)象,如:$route
、$router
、$store
。如果全局使用了ElementUI
后,還可以拿到$message
、$dialog
等等。
以上就是Vue3全局掛載使用Axios學(xué)習(xí)實(shí)戰(zhàn)的詳細(xì)內(nèi)容,更多關(guān)于Vue3全局掛載使用Axios的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Vue 打包的靜態(tài)文件不能直接運(yùn)行的原因及解決辦法
這篇文章主要介紹了Vue 打包的靜態(tài)文件不能直接運(yùn)行的原因及解決辦法,幫助大家更好的理解和學(xué)習(xí)vue框架,感興趣的朋友可以了解下2020-11-11vant-ui AddressEdit地址編輯和van-area的用法說(shuō)明
這篇文章主要介紹了vant-ui AddressEdit地址編輯和van-area的用法說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-11-11Vue動(dòng)畫(huà)之第三方類庫(kù)實(shí)現(xiàn)動(dòng)畫(huà)方式
這篇文章主要介紹了Vue動(dòng)畫(huà)之第三方類庫(kù)實(shí)現(xiàn)動(dòng)畫(huà)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-04-04