Yapei Li

专注于前端领域

0%

Vue+Axios

安装

1
npm install axios

基础使用

结合 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: {
// 封装一个 ajax 方法
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'

// 每次请求携带cookies信息
axios.defaults.withCredentials = true

//(请求头设置)
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';

// 请求超时时间
axios.defaults.timeout = 15000;


// request拦截器
axios.interceptors.request.use(config => {
//看看有没有获取到token(一般登陆成功后存储)
if (window.sessionStorage.getItem('tokenId') && window.sessionStorage.getItem('tokenStr')) {
// 让每个请求携带自定义token 请根据实际情况自行修改
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)
})


// respone拦截器
axios.interceptors.response.use((response) => {
//session过期 (登陆过期)
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){
//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) // for debug
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";
//根据环境变量设置baseUrl
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 {
// 处理错误
}
});

// 取消请求(message 参数是可选的)
source.cancel('Operation canceled by the user.');

可以使用同一个 cancel token 取消多个请求