Init project
This commit is contained in:
+115
@@ -0,0 +1,115 @@
|
||||
//除法函数,用来得到精确的除法结果
|
||||
//说明:javascript的除法结果会有误差,在两个浮点数相除的时候会比较明显。这个函数返回较为精确的除法结果。
|
||||
//调用:div(arg1,arg2)
|
||||
//返回值:arg1除以arg2的精确结果
|
||||
export function div(arg1, arg2) {
|
||||
var t1 = 0,
|
||||
t2 = 0,
|
||||
r1,
|
||||
r2;
|
||||
try {
|
||||
t1 = arg1.toString().split(".")[1].length;
|
||||
} catch (e) {
|
||||
t1 = 0;
|
||||
}
|
||||
try {
|
||||
t2 = arg2.toString().split(".")[1].length;
|
||||
} catch (e) {
|
||||
t2 = 0;
|
||||
}
|
||||
r1 = Number(arg1.toString().replace(".", ""));
|
||||
r2 = Number(arg2.toString().replace(".", ""));
|
||||
return mul(r1 / r2, Math.pow(10, t2 - t1));
|
||||
}
|
||||
//乘法函数,用来得到精确的乘法结果
|
||||
//说明:javascript的乘法结果会有误差,在两个浮点数相乘的时候会比较明显。这个函数返回较为精确的乘法结果。
|
||||
//调用:mul(arg1,arg2)
|
||||
//返回值:arg1乘以arg2的精确结果
|
||||
export function mul(arg1, arg2) {
|
||||
var m = 0,
|
||||
s1 = arg1.toString(),
|
||||
s2 = arg2.toString();
|
||||
try {
|
||||
m += s1.split(".")[1].length;
|
||||
} catch (e) {
|
||||
m = 0;
|
||||
}
|
||||
try {
|
||||
m += s2.split(".")[1].length;
|
||||
} catch (e) {
|
||||
m = m || 0;
|
||||
}
|
||||
return (
|
||||
(Number(s1.replace(".", "")) * Number(s2.replace(".", ""))) /
|
||||
Math.pow(10, m)
|
||||
);
|
||||
}
|
||||
|
||||
//加法函数,用来得到精确的加法结果
|
||||
//说明:javascript的加法结果会有误差,在两个浮点数相加的时候会比较明显。这个函数返回较为精确的加法结果。
|
||||
//调用:add(arg1,arg2)
|
||||
//返回值:arg1加上arg2的精确结果
|
||||
export function add(arg1, arg2) {
|
||||
var r1, r2, m, n;
|
||||
try {
|
||||
r1 = arg1.toString().split(".")[1].length;
|
||||
} catch (e) {
|
||||
r1 = 0;
|
||||
}
|
||||
try {
|
||||
r2 = arg2.toString().split(".")[1].length;
|
||||
} catch (e) {
|
||||
r2 = 0;
|
||||
}
|
||||
m = Math.pow(10, Math.max(r1, r2));
|
||||
n = r1 >= r2 ? r1 : r2;
|
||||
return ((arg1 * m + arg2 * m) / m).toFixed(n);
|
||||
}
|
||||
|
||||
//减法函数,用来得到精确的减法结果
|
||||
//说明:javascript的加法结果会有误差,在两个浮点数相加的时候会比较明显。这个函数返回较为精确的减法结果。
|
||||
//调用:sub(arg1,arg2)
|
||||
//返回值:arg1减去arg2的精确结果
|
||||
export function sub(arg1, arg2) {
|
||||
var r1, r2, m, n;
|
||||
try {
|
||||
r1 = arg1.toString().split(".")[1].length;
|
||||
} catch (e) {
|
||||
r1 = 0;
|
||||
}
|
||||
try {
|
||||
r2 = arg2.toString().split(".")[1].length;
|
||||
} catch (e) {
|
||||
r2 = 0;
|
||||
}
|
||||
m = Math.pow(10, Math.max(r1, r2));
|
||||
//动态控制精度长度
|
||||
n = r1 >= r2 ? r1 : r2;
|
||||
return ((arg1 * m - arg2 * m) / m).toFixed(n);
|
||||
}
|
||||
|
||||
function Compute(value) {
|
||||
this.value = value;
|
||||
}
|
||||
Object.assign(Compute.prototype, {
|
||||
add(v) {
|
||||
this.value = add(this.value, v);
|
||||
return this;
|
||||
},
|
||||
sub(v) {
|
||||
this.value = sub(this.value, v);
|
||||
return this;
|
||||
},
|
||||
div(v) {
|
||||
this.value = div(this.value, v);
|
||||
return this;
|
||||
},
|
||||
mul(v) {
|
||||
this.value = mul(this.value, v);
|
||||
return this;
|
||||
}
|
||||
});
|
||||
|
||||
export default function(value) {
|
||||
return new Compute(value);
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import config from '@/utils/mapConfig';
|
||||
|
||||
module.exports = {
|
||||
getLocation() {
|
||||
return uni.getLocation({
|
||||
type: 'wgs84'
|
||||
})
|
||||
},
|
||||
|
||||
getCurAddress(latitude, longitude) {
|
||||
return uni.request({
|
||||
url: 'https://apis.map.qq.com/ws/geocoder/v1/?location=' + latitude + ',' + longitude +
|
||||
'&key=' + config.key
|
||||
});
|
||||
},
|
||||
|
||||
getUrlParam(url, name) {
|
||||
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
|
||||
var r = url.match(reg);
|
||||
if (r != null) return (r[2]);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
const dialog = {
|
||||
confirm: (options) => {
|
||||
uni.showModal({
|
||||
title: '提示',
|
||||
content: options.mes,
|
||||
success(res) {
|
||||
if (res.confirm) {
|
||||
opts()
|
||||
} else if (res.cancel) {}
|
||||
}
|
||||
})
|
||||
},
|
||||
alert: null,
|
||||
// alert: Dialog.alert,
|
||||
notify: null,
|
||||
// notify,
|
||||
loading: {
|
||||
open: () => {
|
||||
uni.showLoading({
|
||||
title: '加载中'
|
||||
})
|
||||
},
|
||||
close: () => {
|
||||
uni.hideLoading()
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// const icons = { error: "操作失败", success: "操作成功" };
|
||||
// Object.keys(icons).reduce((dialog, key) => {
|
||||
// dialog[key] = (mes, obj = {}) => {
|
||||
// return new Promise(function (resolve) {
|
||||
// toast({
|
||||
// mes: mes || icons[key],
|
||||
// timeout: 1000,
|
||||
// icon: key,
|
||||
// callback: () => {
|
||||
// resolve();
|
||||
// },
|
||||
// ...obj
|
||||
// });
|
||||
// });
|
||||
// };
|
||||
// return dialog;
|
||||
// }, dialog);
|
||||
|
||||
dialog.message = (mes = "操作失败", obj = {}) => {
|
||||
return new Promise(function(resolve) {
|
||||
uni.showToast({
|
||||
title: mes,
|
||||
icon: "none",
|
||||
duration: 2000,
|
||||
complete: () => {
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
dialog.toast = (options) => {
|
||||
uni.showToast({
|
||||
title: options.mes,
|
||||
icon: "none",
|
||||
duration: 2000,
|
||||
complete: () => {
|
||||
options.callback ? options.callback() : null
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
dialog.error = (mes) => {
|
||||
uni.showToast({
|
||||
title: mes,
|
||||
icon: "none",
|
||||
duration: 2000
|
||||
});
|
||||
};
|
||||
|
||||
dialog.validateError = (...args) => {
|
||||
validatorDefaultCatch(...args);
|
||||
};
|
||||
|
||||
export function validatorDefaultCatch(err, type = "message") {
|
||||
uni.showToast({
|
||||
title: err.errors[0].message,
|
||||
icon: 'none',
|
||||
duration: 2000
|
||||
})
|
||||
return false
|
||||
}
|
||||
|
||||
export default dialog;
|
||||
+1115
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,7 @@
|
||||
// 应写入腾讯地图的key
|
||||
module.exports = {
|
||||
|
||||
//key: 'LBZBZ-XAJRO-HKYWF-SOACS-HSTYQ-ZUF44'
|
||||
key: 'J2WBZ-WS366-SL2SI-M35IG-IU7OH-4YFKF'
|
||||
|
||||
};
|
||||
@@ -0,0 +1,63 @@
|
||||
// Copyright Joyent, Inc. and other Node contributors.
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a
|
||||
// copy of this software and associated documentation files (the
|
||||
// "Software"), to deal in the Software without restriction, including
|
||||
// without limitation the rights to use, copy, modify, merge, publish,
|
||||
// distribute, sublicense, and/or sell copies of the Software, and to permit
|
||||
// persons to whom the Software is furnished to do so, subject to the
|
||||
// following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included
|
||||
// in all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
|
||||
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
|
||||
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
|
||||
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
|
||||
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
|
||||
// USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
var stringifyPrimitive = function (v) {
|
||||
switch (typeof v) {
|
||||
case 'string':
|
||||
return v
|
||||
|
||||
case 'boolean':
|
||||
return v ? 'true' : 'false'
|
||||
|
||||
case 'number':
|
||||
return isFinite(v) ? v : ''
|
||||
|
||||
default:
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
function stringify(obj, sep, eq, name) {
|
||||
sep = sep || '&'
|
||||
eq = eq || '='
|
||||
if (obj === null) {
|
||||
obj = undefined
|
||||
}
|
||||
|
||||
if (typeof obj === 'object') {
|
||||
return Object.keys(obj).map(function (k) {
|
||||
var ks = stringifyPrimitive(k) + eq
|
||||
if (Array.isArray(obj[k])) {
|
||||
return obj[k].map(function (v) {
|
||||
return ks + stringifyPrimitive(v)
|
||||
}).join(sep)
|
||||
} else {
|
||||
return ks + stringifyPrimitive(obj[k])
|
||||
}
|
||||
}).filter(Boolean).join(sep)
|
||||
|
||||
}
|
||||
|
||||
if (!name) return ''
|
||||
return stringifyPrimitive(name) + eq + stringifyPrimitive(obj)
|
||||
}
|
||||
|
||||
export default stringify
|
||||
@@ -0,0 +1,112 @@
|
||||
import Fly from "flyio/dist/npm/wx";
|
||||
import { handleLoginFailure } from "@/utils";
|
||||
import { VUE_APP_API_URL } from "@/config";
|
||||
import cookie from "@/utils/store/cookie";
|
||||
|
||||
const fly = new Fly()
|
||||
fly.config.baseURL = VUE_APP_API_URL
|
||||
|
||||
fly.interceptors.response.use(
|
||||
response => {
|
||||
// 定时刷新access-token
|
||||
return response;
|
||||
},
|
||||
error => {
|
||||
if (error.toString() == 'Error: Network Error') {
|
||||
console.log('————————')
|
||||
console.log('发送请求失败', error)
|
||||
console.log('————————')
|
||||
handleLoginFailure();
|
||||
return Promise.reject({ msg: "未登录", toLogin: true });
|
||||
}
|
||||
if (error.status == 401) {
|
||||
console.log('————————')
|
||||
console.log('登录失效 401', error)
|
||||
console.log('————————')
|
||||
handleLoginFailure();
|
||||
return Promise.reject({ msg: "未登录", toLogin: true });
|
||||
}
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
|
||||
const defaultOpt = { login: true };
|
||||
|
||||
function baseRequest(options) {
|
||||
|
||||
// 从缓存中获取 token 防止 token 失效后还会继续请求的情况
|
||||
const token = cookie.get('login_status');
|
||||
|
||||
// 合并传参过来的 headers
|
||||
// 如果接口需要登录,携带 token 去请求
|
||||
options.headers = {
|
||||
...options.headers,
|
||||
Authorization: "Bearer " + token
|
||||
}
|
||||
|
||||
// 如果需要登录才可访问的接口没有拿到 token 视为登录失效
|
||||
if (options.login === true && !token) {
|
||||
// 跳转到登录或授权页面
|
||||
handleLoginFailure();
|
||||
// 提示错误信息
|
||||
return Promise.reject({ msg: "未登录", toLogin: true });
|
||||
}
|
||||
// 结构请求需要的参数
|
||||
const { url, params, data, login, ...option } = options
|
||||
|
||||
// 发起请求
|
||||
return fly.request(url, params || data, {
|
||||
...option
|
||||
}).then(res => {
|
||||
const data = res.data || {};
|
||||
if (res.status !== 200) {
|
||||
return Promise.reject({ msg: "请求失败", res, data });
|
||||
}
|
||||
if ([401, 403].indexOf(data.status) !== -1) {
|
||||
handleLoginFailure();
|
||||
return Promise.reject({ msg: res.data.msg, res, data, toLogin: true });
|
||||
} else if (data.status === 200) {
|
||||
return Promise.resolve(data, res);
|
||||
} else {
|
||||
return Promise.reject({ msg: res.data.msg, res, data });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* http 请求基础类
|
||||
* 参考文档 https://www.kancloud.cn/yunye/axios/234845
|
||||
*
|
||||
*/
|
||||
const request = ["post", "put", "patch"].reduce((request, method) => {
|
||||
/**
|
||||
*
|
||||
* @param url string 接口地址
|
||||
* @param data object get参数
|
||||
* @param options object axios 配置项
|
||||
* @returns {AxiosPromise}
|
||||
*/
|
||||
request[method] = (url, data = {}, options = {}) => {
|
||||
return baseRequest(
|
||||
Object.assign({ url, data, method }, defaultOpt, options)
|
||||
);
|
||||
};
|
||||
return request;
|
||||
}, {});
|
||||
|
||||
["get", "delete", "head"].forEach(method => {
|
||||
/**
|
||||
*
|
||||
* @param url string 接口地址
|
||||
* @param params object get参数
|
||||
* @param options object axios 配置项
|
||||
* @returns {AxiosPromise}
|
||||
*/
|
||||
request[method] = (url, params = {}, options = {}) => {
|
||||
return baseRequest(
|
||||
Object.assign({ url, params, method }, defaultOpt, options)
|
||||
);
|
||||
};
|
||||
});
|
||||
|
||||
export default request;
|
||||
@@ -0,0 +1,62 @@
|
||||
import { trim, isType } from "@/utils";
|
||||
|
||||
const doc = null;
|
||||
// const doc = window.document;
|
||||
|
||||
function get(key) {
|
||||
if (!key || !_has(key)) {
|
||||
return null;
|
||||
}
|
||||
return uni.getStorageSync(key)
|
||||
}
|
||||
|
||||
function all() {
|
||||
return uni.getStorageInfoSync()
|
||||
}
|
||||
|
||||
function set(key, data, time) {
|
||||
if (!key) {
|
||||
return;
|
||||
}
|
||||
uni.setStorageSync(key, data)
|
||||
}
|
||||
|
||||
function remove(key) {
|
||||
if (!key || !_has(key)) {
|
||||
return;
|
||||
}
|
||||
uni.removeStorageSync(key)
|
||||
}
|
||||
|
||||
function clearAll() {
|
||||
// uni.clearStorage()
|
||||
const res = uni.getStorageInfoSync();
|
||||
res.keys.map((item) => {
|
||||
//不要清除spread和redirect
|
||||
if (item == 'redirect' || item == 'spread') {
|
||||
return
|
||||
}
|
||||
remove(item)
|
||||
})
|
||||
console.log(res)
|
||||
}
|
||||
|
||||
function _has(key) {
|
||||
if (!key) {
|
||||
return
|
||||
}
|
||||
let value = uni.getStorageSync(key)
|
||||
if (value) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
export default {
|
||||
get,
|
||||
all,
|
||||
set,
|
||||
remove,
|
||||
clearAll,
|
||||
has: _has
|
||||
};
|
||||
@@ -0,0 +1,7 @@
|
||||
import cookie from "./cookie";
|
||||
import localStorage from "./localStorage";
|
||||
|
||||
export default {
|
||||
cookie,
|
||||
localStorage
|
||||
};
|
||||
@@ -0,0 +1,42 @@
|
||||
function localStorage() {
|
||||
return window.localStorage;
|
||||
}
|
||||
|
||||
function get(key) {
|
||||
return JSON.parse(localStorage().getItem(key));
|
||||
}
|
||||
|
||||
function set(key, data) {
|
||||
return localStorage().setItem(key, JSON.stringify(data));
|
||||
}
|
||||
|
||||
function all() {
|
||||
const data = {};
|
||||
for (var i = localStorage().length - 1; i >= 0; i--) {
|
||||
var key = localStorage().key(i);
|
||||
data[key] = get(key);
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
function remove(key) {
|
||||
return localStorage().removeItem(key);
|
||||
}
|
||||
|
||||
function clearAll() {
|
||||
return localStorage().clear();
|
||||
}
|
||||
|
||||
function has(key) {
|
||||
return localStorage().getItem(key) !== null;
|
||||
}
|
||||
|
||||
export default {
|
||||
get,
|
||||
set,
|
||||
all,
|
||||
remove,
|
||||
clearAll,
|
||||
has
|
||||
};
|
||||
@@ -0,0 +1,177 @@
|
||||
const bindMessage = (fn, message) => {
|
||||
fn.message = field => message.replace("%s", field || "");
|
||||
};
|
||||
|
||||
export function required(message, opt = {}) {
|
||||
return {
|
||||
required: true,
|
||||
message,
|
||||
type: "string",
|
||||
...opt
|
||||
};
|
||||
}
|
||||
|
||||
bindMessage(required, "请输入%s");
|
||||
|
||||
export function url(message, opt = {}) {
|
||||
return {
|
||||
type: "url",
|
||||
message,
|
||||
...opt
|
||||
};
|
||||
}
|
||||
|
||||
bindMessage(url, "请输入正确的链接");
|
||||
|
||||
export function email(message, opt = {}) {
|
||||
return {
|
||||
type: "email",
|
||||
message,
|
||||
...opt
|
||||
};
|
||||
}
|
||||
|
||||
bindMessage(email, "请输入正确的邮箱地址");
|
||||
|
||||
/**
|
||||
* 验证字段必须完全由字母构成。
|
||||
*
|
||||
* @param message
|
||||
* @returns {*}
|
||||
*/
|
||||
export function alpha(message) {
|
||||
return attrs.pattern(/^[\w]+$/, message);
|
||||
}
|
||||
|
||||
bindMessage(alpha, "%s必须是字母");
|
||||
|
||||
/**
|
||||
* 只能包含由字母、数字,以及 - 和 _
|
||||
*
|
||||
* @param message
|
||||
* @returns {*}
|
||||
*/
|
||||
export function alpha_dash(message) {
|
||||
return attrs.pattern(/^[\w\d_-]+$/, message);
|
||||
}
|
||||
|
||||
bindMessage(alpha_dash, "%s只能包含由字母、数字,以及 - 和 _");
|
||||
|
||||
/**
|
||||
* 必须是完全是字母、数字
|
||||
*
|
||||
* @param message
|
||||
* @returns {*}
|
||||
*/
|
||||
export function alpha_num(message) {
|
||||
return attrs.pattern(/^[\w\d]+$/, message);
|
||||
}
|
||||
|
||||
bindMessage(alpha_num, "%s只能包含字母、数字");
|
||||
/**
|
||||
* 正确的金额
|
||||
*
|
||||
* @param message
|
||||
* @returns {*}
|
||||
*/
|
||||
export function num(message) {
|
||||
return attrs.pattern(
|
||||
/(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
|
||||
message
|
||||
);
|
||||
}
|
||||
|
||||
bindMessage(num, "%s格式不正确");
|
||||
|
||||
/**
|
||||
* 只能是汉字
|
||||
* @param message
|
||||
* @returns {*}
|
||||
*/
|
||||
export function chs(message) {
|
||||
return attrs.pattern(/^[\u4e00-\u9fa5]+$/, message);
|
||||
}
|
||||
|
||||
bindMessage(chs, "%s只能是汉字");
|
||||
|
||||
/**
|
||||
* 只能包含汉字、字母
|
||||
* @param message
|
||||
* @returns {*}
|
||||
*/
|
||||
export function chs_alpha(message) {
|
||||
return attrs.pattern(/^[\u4e00-\u9fa5\w]+$/, message);
|
||||
}
|
||||
|
||||
bindMessage(chs_alpha, "%s只能包含汉字、字母");
|
||||
|
||||
/**
|
||||
* 只能包含汉字、字母和数字
|
||||
* @param message
|
||||
* @returns {*}
|
||||
*/
|
||||
export function chs_alpha_num(message) {
|
||||
return attrs.pattern(/^[\u4e00-\u9fa5\w\d]+$/, message);
|
||||
}
|
||||
|
||||
bindMessage(chs_alpha_num, "%s只能包含汉字、字母和数字");
|
||||
|
||||
/**
|
||||
* 只能包含由汉字、字母、数字,以及 - 和 _
|
||||
* @param message
|
||||
* @returns {*}
|
||||
*/
|
||||
export function chs_dash(message) {
|
||||
return attrs.pattern(/^[\u4e00-\u9fa5\w\d-_]+$/, message);
|
||||
}
|
||||
|
||||
bindMessage(chs_dash, "%s只能包含由汉字、字母、数字,以及 - 和 _");
|
||||
|
||||
/**
|
||||
* 手机号验证
|
||||
* @param message
|
||||
* @returns {*}
|
||||
*/
|
||||
export function chs_phone(message) {
|
||||
return attrs.pattern(/^1(3|4|5|7|8|9|6)\d{9}$/i, message);
|
||||
}
|
||||
bindMessage(chs_phone, "请输入正确的手机号码");
|
||||
|
||||
/**
|
||||
* 手机号与座机号验证
|
||||
* @param message
|
||||
* @returns {*}
|
||||
*/
|
||||
export function chs_extphone(message) {
|
||||
return attrs.pattern(/^[\d_-]+$/i, message);
|
||||
}
|
||||
bindMessage(chs_extphone, "请输入正确的联系电话");
|
||||
|
||||
const baseAttr = {
|
||||
min: "%s最小长度为:min",
|
||||
max: "%s最大长度为:max",
|
||||
length: "%s长度必须为:length",
|
||||
range: "%s长度为:range",
|
||||
pattern: "$s格式错误"
|
||||
};
|
||||
|
||||
const attrs = Object.keys(baseAttr).reduce((attrs, key) => {
|
||||
attrs[key] = (attr, message = "", opt = {}) => {
|
||||
const _attr =
|
||||
key === "range" ? { min: attr[0], max: attr[1] } : { [key]: attr };
|
||||
|
||||
return {
|
||||
message: message.replace(
|
||||
`:${key}`,
|
||||
key === "range" ? `${attr[0]}-${attr[1]}` : attr
|
||||
),
|
||||
type: "string",
|
||||
..._attr,
|
||||
...opt
|
||||
};
|
||||
};
|
||||
bindMessage(attrs[key], baseAttr[key]);
|
||||
return attrs;
|
||||
}, {});
|
||||
|
||||
export default attrs;
|
||||
@@ -0,0 +1,187 @@
|
||||
;(function(root, factory) {
|
||||
if (typeof define === 'function' && define.amd) {
|
||||
define([], factory);
|
||||
} else if (typeof exports === 'object') {
|
||||
module.exports = factory();
|
||||
} else {
|
||||
root.vueJsonp = factory();
|
||||
}
|
||||
}(this, function() {
|
||||
/**
|
||||
* Vue Jsonp By LancerComet at 16:35, 2016.10.17.
|
||||
* # Carry Your World #
|
||||
*
|
||||
* @author: LancerComet
|
||||
* @license: MIT
|
||||
*/
|
||||
|
||||
var _timeout = null
|
||||
|
||||
var vueJsonp = {
|
||||
install: function (Vue, options) {
|
||||
Vue.jsonp = jsonp
|
||||
Vue.prototype.$jsonp = jsonp
|
||||
|
||||
if (typeof options === 'number') {
|
||||
_timeout = options
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* JSONP function.
|
||||
* @param { String } url Target URL address.
|
||||
* @param { Object } params Querying params object.
|
||||
* @param { Number } timeout Timeout setting (ms).
|
||||
*
|
||||
* @example
|
||||
* Vue.jsonp('/url', {
|
||||
* callbackQuery: ''
|
||||
* callbackName: '',
|
||||
* name: 'LancerComet',
|
||||
* age: 26
|
||||
* }, 1000)
|
||||
*/
|
||||
function jsonp (url, params, timeout) {
|
||||
params = params || {}
|
||||
timeout = timeout || _timeout
|
||||
|
||||
return new Promise(function (resolve, reject) {
|
||||
if (typeof url !== 'string') {
|
||||
throw new Error('[Vue.jsonp] Type of param "url" is not string.')
|
||||
}
|
||||
|
||||
var callbackQuery = params.callbackQuery || 'callback'
|
||||
var callbackName = params.callbackName || 'jsonp_' + randomStr()
|
||||
|
||||
params[callbackQuery] = callbackName
|
||||
|
||||
// Remove callbackQuery and callbackName.
|
||||
delete params.callbackQuery
|
||||
delete params.callbackName
|
||||
|
||||
// Convert params to querying str.
|
||||
var queryStrs = []
|
||||
Object.keys(params).forEach(function (queryName) {
|
||||
queryStrs = queryStrs.concat(formatParams(queryName, params[queryName]))
|
||||
})
|
||||
|
||||
var queryStr = flatten(queryStrs).join('&')
|
||||
|
||||
// Timeout timer.
|
||||
var timeoutTimer = null
|
||||
|
||||
// Setup timeout.
|
||||
if (typeof timeout === 'number') {
|
||||
timeoutTimer = setTimeout(function () {
|
||||
removeErrorListener()
|
||||
headNode.removeChild(paddingScript)
|
||||
delete window[callbackName]
|
||||
reject({ statusText: 'Request Timeout', status: 408 })
|
||||
}, timeout)
|
||||
}
|
||||
|
||||
// Create global function.
|
||||
window[callbackName] = function (json) {
|
||||
clearTimeout(timeoutTimer)
|
||||
removeErrorListener()
|
||||
headNode.removeChild(paddingScript)
|
||||
resolve(json)
|
||||
delete window[callbackName]
|
||||
}
|
||||
|
||||
// Create script element.
|
||||
var headNode = document.querySelector('head')
|
||||
var paddingScript = document.createElement('script')
|
||||
|
||||
// Add error listener.
|
||||
paddingScript.addEventListener('error', onError)
|
||||
|
||||
// Append to head element.
|
||||
paddingScript.src = url + (/\?/.test(url) ? '&' : '?') + queryStr
|
||||
headNode.appendChild(paddingScript)
|
||||
|
||||
/**
|
||||
* Padding script on-error event.
|
||||
* @param {Event} event
|
||||
*/
|
||||
function onError (event) {
|
||||
removeErrorListener()
|
||||
clearTimeout(timeoutTimer)
|
||||
reject({
|
||||
status: 400,
|
||||
statusText: 'Bad Request'
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove on-error event listener.
|
||||
*/
|
||||
function removeErrorListener () {
|
||||
paddingScript.removeEventListener('error', onError)
|
||||
}
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate random string.
|
||||
* @return { String }
|
||||
*/
|
||||
function randomStr () {
|
||||
return (Math.floor(Math.random() * 100000) * Date.now()).toString(16)
|
||||
}
|
||||
|
||||
/**
|
||||
* Format params into querying string.
|
||||
* @param {{}}
|
||||
* @return {string[]}
|
||||
*/
|
||||
function formatParams (queryName, value) {
|
||||
queryName = queryName.replace(/=/g, '')
|
||||
var result = []
|
||||
|
||||
switch (value.constructor) {
|
||||
case String:
|
||||
case Number:
|
||||
case Boolean:
|
||||
result.push(encodeURIComponent(queryName) + '=' + encodeURIComponent(value))
|
||||
break
|
||||
|
||||
case Array:
|
||||
value.forEach(function (item) {
|
||||
result = result.concat(formatParams(queryName + '[]=', item))
|
||||
})
|
||||
break
|
||||
|
||||
case Object:
|
||||
Object.keys(value).forEach(function (key) {
|
||||
var item = value[key]
|
||||
result = result.concat(formatParams(queryName + '[' + key + ']', item))
|
||||
})
|
||||
break
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* Flat querys.
|
||||
*
|
||||
* @param {any} array
|
||||
* @returns
|
||||
*/
|
||||
function flatten (array) {
|
||||
var querys = []
|
||||
array.forEach(function (item) {
|
||||
if (typeof item === 'string') {
|
||||
querys.push(item)
|
||||
} else {
|
||||
querys = querys.concat(flatten(item))
|
||||
}
|
||||
})
|
||||
return querys
|
||||
}
|
||||
|
||||
return vueJsonp;
|
||||
}));
|
||||
Reference in New Issue
Block a user