import axios from 'axios'
import router from '../router'
// 全局 loading 状态可以共用在大部分组件中,如:
// <el-table v-loading="$store.state.loading"></el-table>
import store from '../store'
// 基本定义
Object.assign(axios.defaults, {
headers: {
'Content-Type': 'application/json',
},
baseURL: '/api',
})
// 请求拦截器添加 headers 添加认证信息
axios.interceptors.request.use((config) => {
if (store.state.user.password) {
config.auth = {
username: store.state.user.password,
}
} else {
// 是否需要跳转到登录认证页
}
store.dispatch('LOADING', true)
return config
}, (error) => {
console.warn('Request Error: ', error)
})
// handleError
function handleError(error) {
const status = error.response && error.response.status
// 修改请求状态
store.dispatch('LOADING', false)
// 跳到登录页面
if (status === 401) {
// 清空登录信息
store.dispatch('LOG_IN', {})
router.push({ path: '/login', query: { to: router.fullPath } })
} else {
return Promise.reject(error)
}
}
// 响应拦截器检测错误
axios.interceptors.response.use((response) => {
// 修改请求状态
store.dispatch('LOADING', false)
return response
}, handleError)
// Vue 插件安装
function install(Vue) {
// 方便进行 this.$httpGet('/data', { _limit: 10, _page: 1 }).then(cb) 快速添加查询
Vue.prototype.$httpGet = (url, params) => axios.get(url, { params })
Vue.prototype.$httpPost = axios.post
Vue.prototype.$httpPut = axios.put
Vue.prototype.$httpDelete = axios.delete
Vue.prototype.$axios = axios
}
axios.install = install
export default axios
如何使用?
main.js
import Vue from 'vue'
import api from '~/lib/api'
Vue.use(api)
...
或者使用一个安装器
// common/mount.js
import SelfButton from '../components/SelfButton.vue'
import API from '../lib/api'
export default (Vue) => {
// 注册用的比较多的组件
Vue.component(SelfButton.name, SelfButton)
// 安装 Axios
Vue.prototype.$httpGet = (url, params) => API.get(url, { params })
Vue.prototype.$httpPost = API.post
Vue.prototype.$httpPut = API.put
Vue.prototype.$httpDelete = API.delete
Vue.prototype.$axios = API
}
// main.js
import Mount from './common/mount'
Vue.use(Mount)
overview.vue
<template>
<div class="over-view">
<self-button :loading="$store.state.loading" @click="load">
开始请求
</self-button>
</div>
</template>
...
<script>
export default {
data() {
return {}
},
methods: {
load() {
this.$axios.post('/login', { username: 'x', password: 'y' }).then().catch()
},
},
created() {
this.$httpGet('/list/book', { _limit: 100, _page: 1, name_like: '高等数学'}).then((response) => {
console.log('res', response.data)
}).catch((error) => {
console.log('error', error)
})
},
}
</script>