This article brings you an introduction (code) about the encapsulation of axios requests in Vue. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
1. Send request module directory
2./api/url stores the URL of each module
// 商品模块 product.js const product = { sku: { list: '/product/product/speclist', options: '/product/product/options' } } export default product // 公用请求模块 common.js const common = { region: { provinces: '/region/region/list', cities: '/region/region/list' }, upload: { image: '/product/product/upload' } } export default common
Send When requesting, you only need to specify the key (sku/list), such as: this.$ajax('sku/list', param); assuming that the baseURL set by axios is http://prod.storm.com/api/, then in the end Request address: http://prod.storm.com/api/pro...
Use the require.context provided by webpack to src/api/url Import all files with the suffix js and sort out an object.
let urls = {} const req = require.context('./url', false, /\.js$/) const requireAll = requireContext => requireContext.keys().map(i => { let url = requireContext(i) Object.assign(urls, url.default) }) requireAll(req) export default urls
Integrate common.js & product.js, the final object is as follows:
urls = { sku: { list: '/product/product/speclist', options: '/product/product/options' }, region: { provinces: '/region/region/list', cities: '/region/region/list' }, upload: { image: '/product/product/upload' } }
import axios from 'axios' import qs from 'qs' import jsd from 'js-file-download' import store from '@/store' import urlObj from './requireURLs' import { Message, MessageBox } from 'element-ui' import { getToken } from '@/utils/auth' const service = axios.create({ baseURL: `${process.env.BASE_API}/api/`, // 不同环境(dev/prod/test)使用不同的baseURL timeout: 5000 }) service.interceptors.request.use( config => { // 上传文件时,config.data的数据类型是FormData, // qs.stringify(FormData)的结果是空字符串,导致报出上传文件为空的错误 if (config.method === 'post' && config.data.constructor !== FormData) { config.data = qs.stringify(config.data) } if (store.getters.token) { config.headers.common['Auth-Token'] = getToken() // Auth-Token 登录过期后,重新登录不传token if (!config.headers.common['Auth-Token']) { delete config.headers.common['Auth-Token'] } } return config }, error => { Promise.reject(error) } ) service.interceptors.response.use( response => { const res = response.data if (response.headers['content-type'].indexOf('application/vnd.ms-excel') !== -1) { let fileName = response.headers['content-disposition'].split('=')[1] jsd(res, fileName) return } if (res.code === 0) { // 和后台约定code:0代表请求成功 return res } else { if (res.code === 18500) { // 和后台约定code:18500代表token未过期,但是被更新了 handleLogin('您已被登出,请重新登录') } else if (res.code === 18501) { // 和后台约定code:18500代表token过期 handleLogin('登录已失效,请重新登录') } else { // 统一处理接口的报错信息,如果需要具体到页面去处理,可以和后台另外约定一个code Message({ message: res.msg, type: 'error', duration: 3 * 1000 }) } return Promise.reject(res) } }, error => { console.log('err ' + error) let data = error.response.data Message({ message: data.msg, type: 'error', duration: 3 * 1000 }) return Promise.reject(data) } ) const handleLogin = title => { MessageBox.confirm(title, '提示', { confirmButtonText: '重新登录', showCancelButton: false, showClose: false, type: 'warning' }).then(() => { store.dispatch('FedLogout').then(() => { location.reload() }) }) } const ajax = (path, data = {}, options = {}) => { let url = path.indexOf('http') === -1 ? path.split('/').reduce((o, k) => { return o[k] }, urlObj) : path let method = options.method || 'post' let params = { url, method } if (options.method === 'get') { Object.assign(params, { params: data }, options) } else { Object.assign(params, { data }, options) } return service(params) } export default ajax
// ajaxPlugin.js import ajax from '@/api/ajax' let ajaxPlugin = {} ajaxPlugin.install = Vue => { Vue.prototype.$ajax = ajax } export default ajaxPlugin // main.js import ajaxPlugin from '@/plugins/ajaxPlugin' Vue.use(ajaxPlugin)
this.$ajax('sku/list').then(res => {})
This article is over here, you can pay attention to more other exciting content PHP Chinese website's JavaScript video tutorial column!
The above is the detailed content of Introduction to the encapsulation of axios requests in vue (code). For more information, please follow other related articles on the PHP Chinese website!