您的位置:首页 > 产品设计 > UI/UE

Vue 工具类整理 完整案例(可直接使用)

2017-09-30 15:49 405 查看
上一篇博客介绍了,全局使用request工具类!

本次完全独立出来,完整的工具类

import Vue from 'vue'
import router from '../router/index'
let Export = {}
let vue = new Vue({router})

Export.post = function (options) {
options.method = 'POST'
options.url = vue.SERVER_NAME + vue.API_PREFIX + options.url
return Request(options)
};
Export.get = function (options) {
options.method = 'GET'
options.url = vue.SERVER_NAME + vue.API_PREFIX + options.url
return Request(options)
};
Export.put = function (options) {
options.method = 'PUT'
options.url = vue.SERVER_NAME + vue.API_PREFIX + options.url
return Request(options)
};
Export.del = function (options) {
options.method = 'DELETE'
options.url = vue.SERVER_NAME + vue.API_PREFIX + options.url
return Request(options)
};

const Request = function (options) {

let newDef = $.Deferred()
/**
* @url:请求的接口地址
* @method: 请求方式(GET/POST/PUT/DELETE)
* @param: 请求参数{key:val} (id:'11',name:'name')
* @headers: 请求的headers{key:val} (token:aabbccdd)
* @useCache: 缓存(针对GET方式)
* @skipValidation:跳过验证
*/
let url = 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 || true
    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: function (data) {
if (skipValidation) {
newDef.resolve(data)
} else if (handleApiResponseStatus(url, data)) {
newDef.resolve(data)
}
},
error: function (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('哎呦喂!登陆超时')
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('哎呦喂!我找不到页面')
} else if (statu >= 500) {
console.info('哎呦喂!服务器异常')
} else {
console.info('哎呦喂!网络出现异常')
}
}

return newDef.promise()

}
export default Export


工具内部可直接跳转页面 vue.$router.push()

调用的时候,import Request form 'kit'

Request.get({ ··参数同上一章节·· }).then(function (resp) {
console.log(resp)
})

有那些不明白的地方可以直接加我QQ:836059265询问(记得加备注vue···)

我会不定时更新内容,毕竟我也在慢慢深入研究咩···
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: