标签:Axios http router Vue3 import 挂载 全局 data
在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
等等。
欢迎访问:天问博客
标签:Axios,http,router,Vue3,import,挂载,全局,data 来源: https://www.cnblogs.com/tive/p/15602285.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。