vue请求类的封装,基于jQuery版本和Axios,两个版本
来源:互联网 发布:a.i.channel软件 编辑:程序博客网 时间:2024/05/17 23:40
vue中基于jQuery请求类的封装:
/** * 该插件基于JQuery的基础封装的,使用的时请自配JQuery * 使用方法:在页面import该JS文件 * XXX.post({··parameter··}).then((response) =>{ success }) */import Vue from 'vue'import store from '../store'import router from '../router'import message from '../components/toast/message'let Export = {}let vue = new Vue({router})Export.post = function (options) { options.method = 'POST' return Request(options)}Export.get = function (options) { options.method = 'GET' return Request(options)}Export.put = function (options) { options.method = 'PUT' return Request(options)}Export.del = function (options) { options.method = 'DELETE' return Request(options)}const Request = function (options) { let newDef = $.Deferred() store.dispatch('showloader') /** * @url:请求的接口地址 * @method: 请求方式(GET/POST/PUT/DELETE) * @param: 请求参数{key:val} (id:'11',name:'name') * @headers: 请求的headers{key:val} (token:aabbccdd) * @useCache: 缓存(针对GET方式) * @skipValidation:跳过验证 */ let url = vue.SERVER_NAME + vue.API_PREFIX + options.url let method = options.method let param = options.data || true let headers = options.headers || true let useCache = options.cache || true let skipValidation = !!options.skipValidation; if (method !== "GET") { param = (typeof param === "string") ? param : JSON.stringify(param) } $.ajax({ url: url, type: method.toUpperCase(), dataType: "json", contentType: "application/json; charset=utf-8", headers: headers, data: param, cache: !!useCache, success: (data) => { if (skipValidation) { newDef.resolve(data) } else if (handleApiResponseStatus(url, data)) { newDef.resolve(data) } }, error:(request, textStatus) => { handleHttpResponseStatus(url, request.status) } }); /** * 处理接口响应状态 */ function handleApiResponseStatus(url, data){ console.info('handle Api Response Status Error') if (!data || (!data.codeText)) { console.error(url, data) return false } if (data.codeText == "RESULT_LOGIN_EXPIRED") { console.info('哎呦喂!登陆超时') message.msg('哎呦喂!登陆超时') return false } else if (data.codeText == "RESULT_NEED_ADVANCE_AUTH") { console.info('哎呦喂!登陆超时,重新登陆') } else if (data.codeText == "RESULT_NEED_BINDPHONE") { return true } else if (data.codeText == "FORBIDDEN") { console.info('哎呦喂!权限验证失败') return false } return true } /** * 处理HTTP相应状态 */ function handleHttpResponseStatus(url, status) { console.info('handle Http Response Status Error:' + status) let statu = Number(status) if (statu == 404) { console.info('哎呦喂!我找不到页面') message.msg('哎呦喂!我找不到页面') } else if (statu >= 500) { console.info('哎呦喂!服务器异常') console.info('哎呦喂!服务器异常') } else { console.info('哎呦喂!网络出现异常') console.info('哎呦喂!网络出现异常') } } store.dispatch('hideloader') return newDef.promise()}export default Export
----------------------------------------------------------------------------------------
/** * 该工具类基于axios,请自行安装axios和qs * npm install axios * npm install qs * 该工具类借鉴之前看的一篇博客,后期使用过程中做后续优化 * store是状态管理,这里操作loading,不需要的可删除 */import Vue from 'vue'import Axios from 'axios'import Qs from 'qs'import router from '../router'import store from '../store'let vue = new Vue({router})//请求Axios.interceptors.request.use( config => { store.commit('updateLoading', true) return config}, error => { return Promise.reject(error)})//请求返回Axios.interceptors.response.use( response => { return response}, error => { return Promise.reject(error.response)})//http请求const Request = (options) => { //默认配置项 let defaultOptions = { method: options.method, baseURL: vue.SERVER_NAME + vue.API_PREFIX, url: options.url, timeout: 3000, params: Object.assign(options.data), data: Qs.stringify(Object.assign(options.data)), headers: options.method == 'get' ? { 'X-Requested-With': 'XMLHttpRequest', "Accept": "application/json", "Content-Type": "application/json; charset=UTF-8" }:{ 'X-Requested-With': 'XMLHttpRequest', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' } } //对get or !get请求处理 if(options.method == 'get'){ delete defaultOptions.data } else { delete defaultOptions.params } let promise = new Promise(function (resolve, reject) { Axios(defaultOptions).then( (response) =>{ if (handleApiResponseStatus(response)) resolve(response.data) }).catch((response) => { if(handleHttpResponseStatus(response)) reject(response) }) }) return promise}//处理Http响应状态function handleHttpResponseStatus(response) { store.commit('updateLoading', false)}//处理Api响应状态function handleApiResponseStatus(response) { store.commit('updateLoading', false)}export default Request
点击链接加入群【ng-vue】:https://jq.qq.com/?_wv=1027&k=52pOebh
阅读全文
0 0
- vue请求类的封装,基于jQuery版本和Axios,两个版本
- vue 组件的封装之基于axios的ajax请求
- 在Vue-cli里基于axios封装复用请求
- 在 vue-cli 里基于 axios 封装复用请求
- vue-resource+jquery+axios请求
- 基于vue-cli的vue项目之axios的使用5--axios方法发送请求
- vue 插件和axios封装
- vue 中axios的封装
- 基于vue-cli的vue项目之axios的使用2--最基础的请求
- 基于vue-cli的vue项目之axios的使用3--get传参请求
- 基于vue-cli的vue项目之axios的使用4--并发请求
- vue项目中对axios的封装
- vue实力封装axios
- vue axios 二次封装
- vue 封装 axios
- vue项目封装axios
- vue 请求采用axios
- vue axios POST请求中参数以form data和request payload形式的原因
- mongodb安装文档
- 编写i2c驱动-基于Linux3.10
- 晶振负载电容是什么意思?关于晶振负载电容
- JAVA MyEclipse(1)--禁用updating indexes与大幅优化myeclipse的速度&关闭自动更新
- 不使用eclipse自带maven的配置问题
- vue请求类的封装,基于jQuery版本和Axios,两个版本
- String,StringBuffer与StringBuilder的区别??
- 使用 wrk 进行压力测试
- iOS下JS与OC互相调用(四)--JavaScriptCore
- 使用HttpClient进行HTTP BASIC验证
- maven插件异常:Plugin execution not covered by lifecycle configuration
- 如何编写更好的SQL查询:终极指南(上)
- Myeclipse无法正常使用SVN
- 设计一个学生类Student并进行测试