温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

vue中如何实现axios全局使用

发布时间:2020-11-04 16:20:10 来源:亿速云 阅读:197 作者:Leah 栏目:开发技术

vue中如何实现axios全局使用?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

1.结合 vue-axios使用

看了vue-axios的源码,它是按照vue插件的方式去写的。那么结合vue-axios,就可以去使用vue.use方法了

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

import axios from 'axios'
import VueAxios from 'vue-axios'

Vue.use(VueAxios,axios);

之后就可以使用了,在组件文件中的methods里去使用了:

getNewsList(){
   this.axios.get('api/getNewsList').then((response)=>{
    this.newsList=response.data.data;
   }).catch((response)=>{
    console.log(response);
   })
}

2.axios 改写为 Vue 的原型属性(不推荐这样用)

首先在主入口文件main.js中引用,之后挂在vue的原型链上:

import axios from 'axios'

Vue.prototype.$ajax= axios

在组件中使用:

this.$ajax.get('api/getNewsList')
.then((response)=>{
  this.newsList=response.data.data;
}).catch((response)=>{
  console.log(response);
})

结合 Vuex的action

在vuex的仓库文件store.js中引用,使用action添加方法

import Vue from 'Vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)
const store = new Vuex.Store({
 // 定义状态
 state: {
  user: {
   name: 'xiaoming'
  }
 },
 actions: {
  // 封装一个 ajax 方法
  login (context) {
   axios({
    method: 'post',
    url: '/user',
    data: context.state.user
   })
  }
 }
})

export default store

在组件中发送请求的时候,需要使用 this.$store.dispatch

methods: {
 submitForm () {
  this.$store.dispatch('login')
 }
}

补充知识:ElementUI 在VUE中配置 main.js与axios的关系

一、在main.js中:

import ElementUI from 'element-ui'

Vue.use(ElementUI)

二、在main.js中,数据请求axios不能在这里配置

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI