增加基本项目配置

This commit is contained in:
Gao xiaosong
2020-03-15 13:59:43 +08:00
commit 397082cdaf
1117 changed files with 105700 additions and 0 deletions
+115
View File
@@ -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);
}
+103
View File
@@ -0,0 +1,103 @@
// import {
// Confirm as confirm,
// Alert as alert,
// Toast as toast,
// Notify as notify,
// Loading as loading
// } from "vue-ydui/dist/lib.rem/dialog";
// import Dialog from "../../static/vant-weapp/dialog/dialog";
// import notify from "../../static/vant-weapp/notify/notify";
const dialog = {
confirm: (options) => {
wx.showModal({
title: '提示',
content: options.mes,
success() {
if (res.confirm) {
opts()
} else if (res.cancel) {}
}
})
},
alert: null,
// alert: Dialog.alert,
notify: null,
// notify,
loading: {
open: () => {
wx.showLoading({
title: '加载中'
})
},
close: () => {
wx.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) {
wx.showToast({
title: mes,
icon: "none",
duration: 2000,
complete: () => {
resolve();
}
});
});
};
dialog.toast = (options) => {
wx.showToast({
title: options.mes,
icon: "none",
duration: 2000,
complete: () => {
options.callback ? options.callback() : null
}
});
};
dialog.error = (mes) => {
wx.showToast({
title: mes,
icon: "none",
duration: 2000
});
};
dialog.validateError = (...args) => {
validatorDefaultCatch(...args);
};
export function validatorDefaultCatch(err, type = "message") {
wx.showToast({
title: err.errors[0].message,
icon: 'none',
duration: 2000
})
return false
}
export default dialog;
+469
View File
@@ -0,0 +1,469 @@
// import Vue from 'vue'
// import MpvueRouterPatch from 'mpvue-router-patch'
// Vue.use(MpvueRouterPatch)
import {
wxappAuth,
getUser
} from "@/api/user";
import store from "../store";
import dayjs from "dayjs";
import cookie from "@/utils/store/cookie";
import stringify from "@/utils/querystring";
export function dataFormat(time, option) {
time = +time * 1000;
const d = new Date(time);
const now = new Date().getTime();
const diff = (now - d) / 1000;
if (diff < 30) {
return "刚刚";
} else if (diff < 3600) {
// less 1 hour
return Math.ceil(diff / 60) + "分钟前";
} else if (diff < 3600 * 24) {
return Math.ceil(diff / 3600) + "小时前";
} else if (diff < 3600 * 24 * 2) {
return "1天前";
}
if (option) {
// return parseTime(time, option);
} else {
let timeStr = d.getFullYear() + "年" + (d.getMonth() + 1) + "月" + d.getDate() + "日" + d.getHours() + "时" + d.getMinutes() +
"分"
return timeStr
}
}
export function dataFormatT(time) {
time = +time * 1000;
const d = new Date(time);
return (
d.getFullYear() +
"/" +
(d.getMonth() + parseInt(1)) +
"/" +
d.getDate()
);
}
export function trim(str) {
return String.prototype.trim.call(str);
}
export function isType(arg, type) {
return Object.prototype.toString.call(arg) === "[object " + type + "]";
}
export function isWeixin() {
// return navigator.userAgent.toLowerCase().indexOf("micromessenger") !== -1;
return false
}
export function parseQuery() {
var pages = getCurrentPages() //获取加载的页面
var currentPage = pages[pages.length - 1] //获取当前页面的对象
var url = currentPage.route //当前页面url
var options = currentPage.options //如果要获取url中所带的参数可以查看options
return options
}
/*获取当前页url*/
export function getCurrentPageUrl() {
var pages = getCurrentPages() //获取加载的页面
var currentPage = pages[pages.length - 1] //获取当前页面的对象
var url = currentPage.route //当前页面url
return url
}
/*获取当前页带参数的url*/
export function getCurrentPageUrlWithArgs() {
var pages = getCurrentPages() //获取加载的页面
var currentPage = pages[pages.length - 1] //获取当前页面的对象
var url = currentPage.route //当前页面url
var options = currentPage.options //如果要获取url中所带的参数可以查看options
//拼接url的参数
var urlWithArgs = url + '?'
for (var key in options) {
var value = options[key]
urlWithArgs += key + '=' + value + '&'
}
urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1)
return urlWithArgs
}
// 复制到剪切板
export const copyClipboard = (data) => {
wx.setClipboardData({
data: data,
success: (res) => {
wx.showToast({
title: '复制成功',
icon: 'success',
duration: 2000
})
}
})
}
export const toAuthorization = (msg) => {
wx.hideLoading();
wx.showToast({
title: msg,
icon: 'none',
duration: 2000
});
console.log(222222222)
replace({
path: '/pages/user/Login/index',
query: {
redirect: `/${getCurrentPageUrl()}`,
...parseQuery()
}
})
}
export const login = (option) => {
console.log('调用登录')
return new Promise((resolve, reject) => {
wx.login({
success: res => {
console.log('获取code')
let code = res.code;
store.commit("UPDATE_WXCODE", res.code);
if (code) {
wx.getSetting({
success: resCode => {
// * 验证授权
if (resCode.authSetting["scope.userInfo"]) {
wx.showLoading({
title: "加载中"
});
wx.getUserInfo({
success: user => {
wxappAuth({
encryptedData: user.encryptedData,
iv: user.iv,
code: code,
spread: cookie.get("spread")
}).then(({
data
}) => {
resolve(res.data)
wx.hideLoading();
store.commit("LOGIN", data.token, dayjs(data.expires_time));
getUser().then(res => {
store.dispatch('changeUserInfo', {
user: res.data
})
});
var pages = getCurrentPages() //获取加载的页面
var currentPage = pages[pages.length - 1] //获取当前页面的对象
let url = "/pages/launch/main?type=0"
let query = {}
if (currentPage) {
if (currentPage.route != 'pages/Loading/index' && currentPage.route !=
'pages/user/Login/index') {
url = currentPage.route
}
if (currentPage.route == 'pages/user/Login/index') {
const {
redirect,
...querys
} = currentPage.options
url = redirect
query = { ...querys
}
}
}
replace({
path: url,
query
});
}).catch(error => {
reject()
option && option.fail ? option.fail() : toAuthorization('获取用户信息失败,请重试')
});
},
fail: error => {
reject()
option && option.fail ? option.fail() : toAuthorization('获取用户信息失败,请重试')
}
});
} else {
store.commit("UPDATE_AUTHORIZATION", false);
reject()
option && option.fail ? option.fail() : toAuthorization('获取用户信息失败,请重试')
}
}
});
} else {
reject()
option && option.fail ? option.fail() : toAuthorization('获取用户信息失败,请重试')
}
},
fail: error => {
reject()
option && option.fail ? option.fail() : toAuthorization('获取用户信息失败,请重试')
}
});
})
}
export function parseUrl(location) {
if (typeof location === 'string') return location
const {
path,
query
} = location
const queryStr = stringify(query)
if (!queryStr) {
return path
}
return `${path}?${queryStr}`
}
export function parseRoute($mp) {
const _$mp = $mp || {}
const path = _$mp.page && _$mp.page.route
return {
path: `/${path}`,
params: {},
query: _$mp.query,
hash: '',
fullPath: parseUrl({
path: `/${path}`,
query: _$mp.query
}),
name: path && path.replace(/\/(\w)/g, ($0, $1) => $1.toUpperCase())
}
}
export function push(location, complete, fail, success) {
let path = ''
if (typeof location === 'string') {
path = location
} else {
path = location.path
}
console.log(path)
if (path != '/pages/launch/index' || path != '/pages/loading/index' || path != '/pages/home/index' || path !=
'/pages/loading/index') {
if (!store.getters.userInfo.uid) {
replace({
path: '/pages/user/Login/index',
query: {
redirect: `/${getCurrentPageUrl()}`,
...parseQuery()
}
})
return
}
}
const url = parseUrl(location)
const params = {
url,
complete,
fail,
success
}
if (location.isTab) {
uni.switchTab(params)
return
}
if (location.reLaunch) {
uni.reLaunch(params)
return
}
uni.navigateTo(params)
}
export function replace(location, complete, fail, success) {
const url = parseUrl(location)
uni.redirectTo({
url,
complete,
fail,
success
})
}
export function go(delta) {
uni.navigateBack({
delta
})
}
export function back() {
uni.navigateBack({
delta: 1,
success: function(e) {},
fail: function(e) {}
})
}
export function switchTab(location, complete, fail, success) {
const url = parseUrl(location)
uni.switchTab({
url,
complete,
fail,
success
})
}
export const _router = {
mode: 'history',
switchTab,
push,
replace,
go,
back
}
export function handleQrCode() {
try {
var urlSpread = parseQuery()["q"];
if (urlSpread) {
// 通过海报二维码进来
urlSpread = urlSpread
.split("%3F")[1]
.replace(/%3D/g, ":")
.replace(/%26/g, ",")
.split(",")
.map((item, index) => {
item = item.split(":");
return `"${item[0]}":"${item[1]}"`;
})
.join(",");
urlSpread = JSON.parse("{" + urlSpread + "}");
return urlSpread
}
return null
} catch {
return null
}
}
const getImageInfo = (images) => {
console.log(images)
return new Promise((resolve, reject) => {
let imageAry = {}
images.map((item, index) => {
wx.getImageInfo({
src: item,
fail: function(res) {
imageAry[index] = null
console.log(res)
if (imageAry.length == images.length) {
resolve(imageAry)
}
},
success: function(res) {
imageAry[index] = res
console.log(res)
if (Object.keys(imageAry).length == images.length) {
resolve(imageAry)
}
}
})
})
})
}
/**
* 获取分享海报
* @param array store 海报素材
* @param string store_name 素材文字
* @param string price 价格
* @param function successFn 回调函数
*
*
*/
export const PosterCanvas = (store, successCallBack) => {
wx.showLoading({
title: '海报生成中',
mask: true
});
getImageInfo([store.image, store.code]).then(res => {
let contentHh = 48 * 1.3
const ctx = wx.createCanvasContext('myCanvas');
ctx.clearRect(0, 0, 0, 0);
const WIDTH = 747
const HEIGHT = 1326;
ctx.fillStyle = "#FFFFFF";
ctx.fillRect(0, 0, WIDTH, HEIGHT);
ctx.drawImage(res[1].path, 40, 1064, 200, 200);
ctx.drawImage(res[0].path, 0, 0, WIDTH, WIDTH);
ctx.save();
let r = 90;
let d = r * 2;
let cx = 40;
let cy = 990;
ctx.arc(cx + r, cy + r, r, 0, 2 * Math.PI);
ctx.clip();
ctx.restore();
ctx.setTextAlign('center');
ctx.setFontSize(48);
ctx.setFillStyle('#000');
ctx.fillText(store.title, WIDTH / 2, 810 + contentHh);
ctx.setTextAlign('center')
ctx.setFontSize(32);
ctx.setFillStyle('red');
ctx.fillText('¥' + store.price, WIDTH / 2, 985);
ctx.setTextAlign('center')
ctx.setFontSize(22);
ctx.setFillStyle('#333333');
ctx.fillText('长按识别二维码立即购买', WIDTH / 2, 1167);
// ctx.drawImage(store.code, 199, 1064, 200, 200);
ctx.save();
ctx.draw(true, function(oi) {
wx.canvasToTempFilePath({
canvasId: 'myCanvas',
fileType: 'png',
destWidth: WIDTH,
destHeight: HEIGHT,
success: function(res) {
wx.hideLoading();
successCallBack && successCallBack(res.tempFilePath);
},
fail: function(error) {
console.log(error)
},
})
});
})
// wx.getImageInfo({
// src: store.image,
// fail: function (res) {
// wx.showToast({
// title: '海报生成失败',
// icon: "none",
// duration: 2000
// });
// },
// success: function (res) {
// }
// })
}
+63
View File
@@ -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
+98
View File
@@ -0,0 +1,98 @@
import Fly from "flyio/dist/npm/wx";
import $store from "../store";
import toLogin from "@/libs/login";
import { VUE_APP_API_URL } from "@/config";
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') {
toLogin();
return Promise.reject({ msg: "未登录", toLogin: true });
}
if (error.status == 401) {
toLogin();
return Promise.reject({ msg: "未登录", toLogin: true });
}
return Promise.reject(error);
}
);
const defaultOpt = { login: true };
function baseRequest(options) {
const token = $store.state.token;
const headers = options.headers || {};
if (options.login) {
headers["Authorization"] = "Bearer " + token;
}
options.headers = headers;
if (options.login && !token) {
toLogin();
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 ([410000, 410001, 410002].indexOf(data.status) !== -1) {
toLogin();
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;
+86
View File
@@ -0,0 +1,86 @@
import { trim, isType } from "@/utils";
const doc = null;
// const doc = window.document;
function get(key) {
if (!key || !_has(key)) {
return null;
}
return wx.getStorageSync(key)
// let regexpStr =
// "(?:^|.*;\\s*)" +
// escape(key).replace(/[-.+*]/g, "\\$&") +
// "\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*";
// return JSON.parse(unescape(doc.cookie.replace(new RegExp(regexpStr), "$1")));
}
function all() {
return wx.getStorageInfoSync()
// let cookies = doc.cookie.split(/; ?/g),
// data = {};
// for (let i = cookies.length - 1; i >= 0; i--) {
// if (!trim(cookies[i])) {
// continue;
// }
// let kvp = cookies[i].split("=");
// let key = unescape(kvp[0]);
// data[key] = unescape(kvp[1]);
// }
// return data;
}
function set(key, data, time) {
if (!key) {
return;
}
// let expires = "Tue, 19 Jan 2038 03:14:07 GMT";
// if (time) {
// let date;
// if (isType(time, "Date")) {
// date = time;
// } else {
// date = new Date();
// date.setTime(date.getTime() + time * 60000);
// }
// expires = date.toGMTString();
// }
// data = JSON.stringify(data);
// doc.cookie =
// escape(key) + "=" + escape(data) + "; expires=" + expires + "; path=/";
wx.setStorageSync(key, data)
}
function remove(key) {
if (!key || !_has(key)) {
return;
}
wx.removeStorageSync(key)
}
function clearAll() {
wx.clearStorage()
}
function _has(key) {
if (!key) {
return
}
let value = wx.getStorageSync(key)
if (value) {
return true
}
return false
}
export default {
get,
all,
set,
remove,
clearAll,
has: _has
};
+7
View File
@@ -0,0 +1,7 @@
import cookie from "./cookie";
import localStorage from "./localStorage";
export default {
cookie,
localStorage
};
+42
View File
@@ -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
};
+167
View File
@@ -0,0 +1,167 @@
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, "请输入正确的手机号码");
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;