Vue 3.x 全局引入axios 方法


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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM