使用vue+vuex+axios封装http请求,使用promise+async+await

目录

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
project

└───utils
│ │ axios.js
│ utils.js
└───config
│ │ config.js
└───services
│ api.js
└───store
│ index.js
└──────modules
│ │ common.js
│ │ user.js
└────────
.......

config.js

1
2
3
4
5
export default {
PRO_URL: 'http://localhost',
PRO_URL: 'http://localhost',
version: '1.0.0',
};

axios.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
import axios from 'axios'
import store from '@/store/index'
import qs from 'qs'
import GlobalConfig from '@/config/config'

let baseUrl = ''
if (process.env.NODE_ENV === 'production') {
// 生产环境操作
baseUrl = GlobalConfig.APP_PRO_URL
} else if (process.env.NODE_ENV === 'development') {
// 测试环境操作
baseUrl = GlobalConfig.APP_DEV_URL
}
axios.defaults.baseURL = baseUrl
// 设置超时时间
axios.defaults.timeout = 10000
// 设置post请求头
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

// 请求拦截器
axios.interceptors.request.use((config) => {
store.dispatch('setShowLoading') // 显示loading
// 设置基本参数
const params = config
const requestData = {}
config.headers.Authorization = store.getters.getUserToken // 把用户凭证放到header里面
requestData.version = APP_CONFIG.APP_VERSION
config.method.toUpperCase() === 'POST'
? config.data = qs.stringify({...config.data, ...requestData})
: config.params = {...config.params, ...requestData}
return params
}, err => Promise.reject(err))

// 响应拦截器
axios.interceptors.response.use((res) => {
store.dispatch('setHideLoading') // 通过state隐藏loading
if (res.status !== 200) {
return Promise.reject(res)
}
if (!res.data) {
return Promise.reject(res)
}
return Promise.resolve(res.data)
}, err => Promise.reject(err))

const httpRequest = (url, params = {}, method = 'GET') => {
if (method.toUpperCase() === 'GET') {
return axios.get(url, {
params
})
} else if (method.toUpperCase() === 'POST') {
return axios.post(url, params)
}
return false
}

export default httpRequest

api.js

1
2
3
import axios from '@/common/utils/axios';

export const test = params => httpRequest('/test/test', params);

配置store

index.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import Vuex from 'vuex'
import Vue from 'vue'
import common from './modules/common'

Vue.use(Vuex)

const store = new Vuex.Store({
strict: process.env.NODE_ENV !== 'production', // 开发环境切换到严格模式
modules: {
common
}
})

export default store

common.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
import Vue from 'vue'

const common = {
state: {
},
mutations: {
SHOW_LOADING: (state, d) => {
// 加载loading操作
},
HIDE_LOADING: (state) => {
// 隐藏loading操作
}
},
actions: {
setShowLoading ({commit, d}) {
commit({
type: 'SHOW_LOADING'
})
},
setHideLoading ({commit}) {
commit('HIDE_LOADING')
},
setHeaderTop ({commit}, value) {
commit('SET_HEADER_TOP', value)
}
}
}

export default common

user.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const user = {
state: {
userToken: ''
},
getters: {
getAccessToken: (state) => {
return state.userToken
}
},
mutations: {
SET_USER_TOKE: (state, userToken) => {
state.userToken = userToken
// 对token的操作,cookie,localStorage等
}
},
actions:
setUserToken ({commit}, userToken) {
commit('SET_USER_TOKE', userToken)
}
}
}

export default user

注册全局$api方法

main.js

1
2
3
4
import Vue from 'vue'
import * as api from '@/services/api'

Vue.prototype.$api = Api

使用async+await请求

index.vue

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
// script
export default {
data() {
return {};
},
components: {},
created() {
this.test();
},
activated() {
},
mounted() {
this.$nextTick(() => {
});
},
computed: {},
watch: {},
methods: {
async test() {
const that = this;
await that.$ajax.test()
.then((res) => {
console.log(res);
});
},
},
};