在vue项目中,经常会使用到axios来与后台进行数据交互,axios丰富的api满足我们基本的需求。但是对于项目而言,每次都需要对异常进行捕获或者处理的话,代码会很繁重冗余。我们需要将其公共部分封装起来,比如异常处理,请求拦截等。本文讲述,如何在vue中封装axios。
废话不多说,上菜:
1、安装axios
npm install axios
2、封装axios
创建utils>request.js文件
import axios from 'axios'
const instance = axios.create({
baseURL: 'https://xxxxxx.com/api',
timeout: 60000
})
const defaultOpt = { login: true }
function baseRequest(options) {
const token = ''; // 请求统一携带token
const headers = options.headers || {}
if (token) {
headers['X-Token'] = token
options.headers = headers
}
return new Promise((resolve, reject) => {
instance(options).then(res => {
const data = res.data || {}
return resolve(data, res)
}).catch(message => reject({ message }));
})
}
const request = ['post', 'put', 'patch', 'delete'].reduce((request, method) => {
request[method] = (url, data = {}, options = {}) => {
return baseRequest(
Object.assign({ url, data, method }, defaultOpt, options)
)
}
return request
}, {});
['get', 'head'].forEach(method => {
request[method] = (url, params = {}, options = {}) => {
return baseRequest(
Object.assign({ url, params, method }, defaultOpt, options)
)
}
})
export default request
3、统一管理api
创建api>index.js文件
import request from './request';
export function getList() {
return request.get(`index/list`)
}
export function create(data) {
return request.post(`index/create`, data)
}
4、使用
<script>
import { getList } from '@/api/index.js'
export default {
mounted() {
getList().then(res => {
console.log(res)
})
}
}
</script>