Vue3学习与实战 · 挂载全局使用Axios
在 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'
// ...
/* 挂载全局对象 start */
Vue.prototype.$http = Axios;
Vue.prototype.$utils = Utils;
/* 挂载全局对象 end */
new Vue({
router,
store,
render: h => h(index)
}).$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 */
Vue.prototype.$http = Axios;
Vue.prototype.$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 。
提示:可以通过打印看到其中有很多全局对象,如: $route 、 $router 、 $store 。如果全局使用了 ElementUI 后,还可以拿到 $message 、 $dialog 等等。
来自:https://www.tiven.cn/p/7f7ba3b2/
本文内容仅供个人学习/研究/参考使用,不构成任何决策建议或专业指导。分享/转载时请标明原文来源,同时请勿将内容用于商业售卖、虚假宣传等非学习用途哦~感谢您的理解与支持!