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)
})

继续踩坑
Vue 3.x 全局引入axios 方法

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

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-06-17
  • 2022-12-23
  • 2021-11-24
猜你喜欢
  • 2018-09-27
  • 2022-12-23
  • 2021-06-10
  • 2021-07-30
  • 2021-11-21
相关资源
相似解决方案