vue 全局引入 axios 大概會在網上找到下面兩種方案:
一、改寫Vue的原型屬性
方法是在main.js中寫入
import { createApp } from 'vue'
import App from './App.vue'
import axios from 'axios'
const app = createApp(App)
app.prototype.$http= axios
經過踩坑,發現vue3.0取消了Vue.prototype,官方文檔推薦使用globalProperties
於是main.js改寫成
import { createApp } from 'vue'
import App from './App.vue'
import axios from 'axios'
const app = createApp(App)
app.config.globalProperties.$http = axios
然后在組件中引用
this.$http.get('api/getNewsList')
.then((response)=>{
console.log(response)
})
繼續踩坑
vue3.0中是沒有this的。使用getCurrentInstance來獲取上下文
const { proxy } = getCurrentInstance() 這里的proxy相當於this
const { proxy } = getCurrentInstance()
proxy.$http.get('api/getNewsList')
.then((response)=>{
console.log(response)
})
二、使用vue-axios插件
首先在主入口文件main.js中引用:
import { createApp } from 'vue'
import App from './App.vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
const app = createApp(App)
app.use(VueAxios,axios);
然后在組件中引用,注意vue3.x沒有this
axios.get('api/getNewsList')
.then((response)=>{
console.log(response)
})
文章來自 Yongchin'blog yongchin.xyz