在vue项目开发中,咱们使用axios进行ajax请求,不少人一开始使用axios的方式,会当成vue-resoure的使用方式来用,即在主入口文件引入import VueResource from 'vue-resource'以后,直接使用Vue.use(VueResource)以后便可将该插件全局引用了,因此axios这样使用的时候就报错了,很懵逼。html
仔细看看文档,就知道axios 是一个基于 promise 的 HTTP 库,axios并无install 方法,因此是不能使用vue.use()方法的。☞查看vue插件
那么难道咱们要在每一个文件都要来引用一次axios吗?多繁琐!!!解决方法有不少种:
1.结合 vue-axios使用
2.axios 改写为 Vue 的原型属性
3.结合 Vuex的actionvue
看了vue-axios的源码,它是按照vue插件的方式去写的。那么结合vue-axios,就能够去使用vue.use方法了ios
首先在主入口文件main.js中引用:ajax
import axios from 'axios' import VueAxios from 'vue-axios' Vue.use(VueAxios,axios);
以后就能够使用了,在组件文件中的methods里去使用了:vuex
getNewsList(){ this.axios.get('api/getNewsList').then((response)=>{ this.newsList=response.data.data; }).catch((response)=>{ console.log(response); }) }
首先在主入口文件main.js中引用,以后挂在vue的原型链上:npm
import axios from 'axios' Vue.prototype.$ajax= axios
在组件中使用:axios
this.$ajax.get('api/getNewsList') .then((response)=>{ this.newsList=response.data.data; }).catch((response)=>{ console.log(response); })
结合 Vuex的action
在vuex的仓库文件store.js中引用,使用action添加方法api
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.dispatchpromise
methods: { submitForm () { this.$store.dispatch('login') } }