当前位置:   article > 正文

Vue 3.x 全局引入axios 方法_vue3全局引入axios

vue3全局引入axios

vue 全局引入 axios 大概会在网上找到下面两种方案:

一、改写Vue的原型属性

方法是在main.js中写入

  1. import { createApp } from 'vue'
  2. import App from './App.vue'
  3. import axios from 'axios'
  4. const app = createApp(App)
  5. app.prototype.$http= axios

经过踩坑,发现vue3.0取消了Vue.prototype,官方文档推荐使用globalProperties
于是main.js改写成

  1. import { createApp } from 'vue'
  2. import App from './App.vue'
  3. import axios from 'axios'
  4. const app = createApp(App)
  5. app.config.globalProperties.$http = axios

然后在组件中引用

  1. this.$http.get('api/getNewsList')
  2. .then((response)=>{
  3. console.log(response)
  4. })

继续踩坑

图片名称

vue3.0中是没有this的。使用getCurrentInstance来获取上下文
const { proxy } = getCurrentInstance() 这里的proxy相当于this

  1. const { proxy } = getCurrentInstance()
  2. proxy.$http.get('api/getNewsList')
  3. .then((response)=>{
  4. console.log(response)
  5. })

二、使用vue-axios插件

首先在主入口文件main.js中引用:

  1. import { createApp } from 'vue'
  2. import App from './App.vue'
  3. import axios from 'axios'
  4. import VueAxios from 'vue-axios'
  5. const app = createApp(App)
  6. app.use(VueAxios,axios);

然后在组件中引用,注意vue3.x没有this

  1. axios.get('api/getNewsList')
  2. .then((response)=>{
  3. console.log(response)
  4. })

 

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号