安装
基础使用
结合 vue-axios使用
man.js
1 2 3 4
| import axios from 'axios' import VueAxios from 'vue-axios'
Vue.use(VueAxios,axios);
|
组件中:
1 2 3 4 5 6 7
| getNewsList(){ this.axios.get('api/getNewsList').then((response)=>{ this.newsList=response.data.data; }).catch((response)=>{ console.log(response); }) }
|
axios 改写为 Vue 的原型属性
main.js
1 2
| import axios from 'axios' Vue.prototype.$http= axios
|
在组件中:
1 2 3 4 5 6
| this.$ajax.get('api/getNewsList') .then((response)=>{ this.newsList=response.data.data; }).catch((response)=>{ console.log(response); })
|
结合 Vuex的action
在vuex的仓库文件store.js
中引用,使用action添加方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| 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: { login (context) { axios({ method: 'post', url: '/user', data: context.state.user }) } } })
export default store
|
在组件中:
1 2 3 4 5
| methods: { submitForm () { this.$store.dispatch('login') } }
|
高阶使用
简易版
不需要再main.js
中使用 Vue.use
,因为不需要再组件中使用this.axios获取
http.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
| import axios from 'axios' import store from '../store' import qs from 'qs' import { getToken } from '@/utils/auth' import { Message, MessageBox } from 'element-ui'
axios.defaults.withCredentials = true
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
axios.defaults.timeout = 15000;
axios.interceptors.request.use(config => { if (window.sessionStorage.getItem('tokenId') && window.sessionStorage.getItem('tokenStr')) { config.headers['tokenId'] = window.sessionStorage.getItem('tokenId'); config.headers['tokenStr'] = window.sessionStorage.getItem('tokenStr'); } if (config.method === 'get') { } if (config.method === 'post') { config.data = qs.stringify(config.data); } return config; }, error => { Promise.reject(error) })
axios.interceptors.response.use((response) => { if (response.data.code == -99 || response.data.code == -88 ) { router.replace({ path: '/login' }); store.commit("increment", true); Message({ message: '请重新登陆', type: 'error', duration: 5 * 1000 }) return; }else if(response.data.code !== 200){ return response; } }, function (error) { if (error.message === 'Network Error' && error.config.url.endsWith('/license')) { Message({ message: '无法连接到本地代理程序,请确认代理程序是否运行正常!', type: 'error', duration: 5 * 1000 }) } else { console.log(error + ' ' + error.config.url) Message({ message: error.message + ' ' + error.config.url, type: 'error', duration: 5 * 1000 }) } return Promise.reject(error); }); export default axios
|
api.js
1 2 3 4 5 6 7 8 9 10 11
| import axios from './utils/http.js' const base = "https://api.m.jd.com";
if(process.env.NODE_ENV=='production'){ base=process.env.BASE_API; }
export const test = params => { return axios.get(`${base}/api`, { params: params }); };
|
组件中使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| import { test } from "../../api/api";
let data = { appid: "jxjd", functionId: "prod4api2gateway_queryCrmRecommend", body: { url: "/prod4api2gateway/api/recommend/queryCrmRecommend", recommendType: "2", source: "4", departNo: "100145", shopId: "50364510", appName: "jxjd" } }; test1(data) .then(res => { console.log("res: ", res); }) .catch(err => { console.log("err: ", err); });
|
取消请求:
可以使用 CancelToken.source 工厂方法创建 cancel token,像这样:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| var CancelToken = axios.CancelToken; var source = CancelToken.source();
axios.get('/user/12345', { cancelToken: source.token }).catch(function(thrown) { if (axios.isCancel(thrown)) { console.log('Request canceled', thrown.message); } else { } });
source.cancel('Operation canceled by the user.');
|
可以使用同一个 cancel token 取消多个请求