# 常用js工具
# request.js
import axios from 'axios'
import { Message, Notification } from 'element-ui'
import store from '@/store'
/**
* 默认通用配置
* request config > instance.defaults > 系统默认,优先级高的覆盖优先级低的。
* @type {AxiosInstance}
*/
const service = axios.create({
baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
// withCredentials: true, // --- 是否携带cookie信息
timeout: 60 * 1000 // 一分钟
})
service.post()
/**
* @param accessUrlPre
*/
/**
* 请求拦截器
*/
service.interceptors.request.use(
config => {
return config
},
error => {
// 处理请求错误
console.log(error) // for debug
return Promise.reject(error)
}
)
/**
* 响应拦截器
*/
service.interceptors.response.use(
response => {
const res = response.data
if (res.code !== 0) {
if (res.msg) {
const msg =
res.msg.length > 50
? process.env.VUE_APP_ERROR_MESSAGE_DEFAULT
: res.msg
if (process.env.NODE_ENV === 'development') {
Notification({
title: '提示',
dangerouslyUseHTMLString: true,
message: response.config.url + ' ' + res.code + '<br />' + msg,
type: 'warning',
showClose: true,
duration: 0
})
} else {
Message.closeAll()
Message({
message: msg,
type: 'error',
showClose: true,
duration: 5 * 1000
})
}
}
return Promise.reject(res, response)
} else {
return res
}
},
error => {
let msg = process.env.VUE_APP_ERROR_MESSAGE_OTHER
const status = error.response && error.response.status
if (status === 403) {
msg = process.env.VUE_APP_ERROR_MESSAGE_403
store.dispatch('user/logout')
}
if (status === 404) {
msg = process.env.VUE_APP_ERROR_MESSAGE_404
}
if (status >= 500) {
msg = process.env.VUE_APP_ERROR_MESSAGE_500
}
if (process.env.NODE_ENV === 'development') {
Notification({
title: '提示',
dangerouslyUseHTMLString: true,
message: error.response.config.url + ' ' + status + '<br />' + msg,
type: 'warning',
showClose: true,
duration: 0
})
} else {
Message.closeAll()
Message({
message: msg,
type: 'error',
showClose: true,
duration: 5 * 1000
})
}
return Promise.reject(error)
}
)
export default service
/**
* get 方式可带参 跨域 请求
* @param { url: url, data: data, cb: fnName }
*/
export function jsonp({ url, data: params, cb }) {
return new Promise(resolve => {
const script = document.createElement('script')
let arrs = []
if (params) {
params = { ...params }
arrs = params.map((value, index) => {
return `${index}=${value}`
})
}
if (arrs && arrs.length > 0) {
script.src = `${url}?${arrs.join('&')}`
} else {
script.src = `${url}`
}
document.body.appendChild(script)
// script.remove() ie不支持,采用parentNode()来removeNode()
script.parentNode.removeChild(script)
resolve(cb)
})
}
# auth.js
import Cookies from 'js-cookie'
import { getAccess } from '@/api/user'
import { jsonp } from './request'
import { Message } from 'element-ui'
const TokenKey = 'user-Token'
export function getToken() {
return Cookies.get(TokenKey)
}
export function setToken(token) {
return Cookies.set(TokenKey, token)
}
export function removeToken() {
return Cookies.remove(TokenKey)
}
/**
* 以请求静态资源的方式 对对其他web进行登录
* @param {*} accessUrlPre 服务登录请求地址 /{token(base64编码)}
* @param {*} preProccess 预处理函数
* @param {*} callBack 回调函数
*/
export function serversAccess(accessUrlPre, preProccess, callBack) {
if (preProccess) {
preProccess()
}
getAccess().then(resp => {
try {
jsonp({ url: accessUrlPre + resp.msg }).then(() => {
const addrs = location.href.split('?')
setTimeout(() => {
if (addrs.length > 1) {
location.href = window.atob(addrs[1])
} else {
if (callBack) {
typeof callBack === 'function' && callBack()
}
}
}, 1000)
})
} catch (err) {
Message({ message: '登录失败,请稍后重试', type: 'error' })
}
})
}
# element-ui.js
import { Loading } from 'element-ui'
/**
* loading加载动画
* 使用
* 开始 const loading = this.$loading()/this.$loading(dom)
* 结束 loading.close()
* @param {*} target 需要loading覆盖的目标(DOM对象)/默认值全局
* 注意: dom 必须是 原生标签
*/
export function loading(target, msg) {
let usedTarget = document.getElementsByTagName('main')[0]
if (target) {
usedTarget = target
}
return Loading.service({
text: msg,
background: 'rgba(255, 255, 255, 0.3)',
target: usedTarget,
spinner: 'my-el-icon-loading'
})
}
# scroll-to.js
Math.easeInOutQuad = function(t, b, c, d) {
t /= d / 2
if (t < 1) {
return c / 2 * t * t + b
}
t--
return -c / 2 * (t * (t - 2) - 1) + b
}
// requestAnimationFrame for Smart Animating http://goo.gl/sx5sts
var requestAnimFrame = (function() {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function(callback) { window.setTimeout(callback, 1000 / 60) }
})()
/**
* Because it's so fucking difficult to detect the scrolling element, just move them all
* @param {number} amount
*/
function move(amount) {
document.documentElement.scrollTop = amount
document.body.parentNode.scrollTop = amount
document.body.scrollTop = amount
}
function position() {
return document.documentElement.scrollTop || document.body.parentNode.scrollTop || document.body.scrollTop
}
/**
* @param {number} to
* @param {number} duration
* @param {Function} callback
*/
export function scrollTo(to, duration, callback) {
const start = position()
const change = to - start
const increment = 20
let currentTime = 0
duration = (typeof (duration) === 'undefined') ? 500 : duration
var animateScroll = function() {
// increment the time
currentTime += increment
// find the value with the quadratic in-out easing function
var val = Math.easeInOutQuad(currentTime, start, change, duration)
// move the document.body
move(val)
// do the animation unless its over
if (currentTime < duration) {
requestAnimFrame(animateScroll)
} else {
if (callback && typeof (callback) === 'function') {
// the animation is done so lets callback
callback()
}
}
}
animateScroll()
}
# validate.js
/**
* Created by PanJiaChen on 16/11/18.
*/
/**
* @param {string} path
* @returns {Boolean}
*/
export function isExternal(path) {
return /^(https?:|mailto:|tel:)/.test(path)
}
/**
* @param {string} str
* @returns {Boolean}
*/
export function validUsername(str) {
const valid_map = ['admin', 'editor']
return valid_map.indexOf(str.trim()) >= 0
}
/**
* @param {string} url
* @returns {Boolean}
*/
export function validURL(url) {
const reg = /^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/
return reg.test(url)
}
/**
* @param {string} str
* @returns {Boolean}
*/
export function validLowerCase(str) {
const reg = /^[a-z]+$/
return reg.test(str)
}
/**
* @param {string} str
* @returns {Boolean}
*/
export function validUpperCase(str) {
const reg = /^[A-Z]+$/
return reg.test(str)
}
/**
* @param {string} str
* @returns {Boolean}
*/
export function validAlphabets(str) {
const reg = /^[A-Za-z]+$/
return reg.test(str)
}
/**
* @param {string} email
* @returns {Boolean}
*/
export function validEmail(email) {
const reg = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
return reg.test(email)
}
/**
* @param {string} str
* @returns {Boolean}
*/
export function isString(str) {
if (typeof str === 'string' || str instanceof String) {
return true
}
return false
}
/**
* @param {Array} arg
* @returns {Boolean}
*/
export function isArray(arg) {
if (typeof Array.isArray === 'undefined') {
return Object.prototype.toString.call(arg) === '[object Array]'
}
return Array.isArray(arg)
}
/**
* 判断非空
* @param arg
* @returns {boolean}
*/
export function isNotNull(arg) {
if (typeof arg === 'undefined' || arg === null || arg === '') {
return false
}
return true
}
/**
* 0~1之间的小数
* @param arg
* @returns {boolean}
*/
export function isDecimal_0To1(arg) {
if (!Number(arg)) {
return false
} else {
if (arg < 0 || arg > 1) {
return false
} else {
return true
}
}
}
/**
* 是否正整数
* @param arg
* @returns {boolean}
*/
export function isIntegerNotMust(arg) {
if (!Number(arg)) {
return false
} else {
const re = /^[0-9]*[1-9][0-9]*$/
const rsCheck = re.test(arg)
if (!rsCheck) {
return false
} else {
return true
}
}
}
/**
* 验证字符长度
* @param arg
* @returns {boolean}
*/
export function validateStrLength(arg, min, max) {
const str = arg.toString()
if (str.length > max || str.length < min) {
return false
} else {
return true
}
}
/**
* 验证手机号
* @export
* @param {*} phone
* @returns
*/
export function validatePhone(phone) {
const reg = /^1[3456789]\d{9}$/
return reg.test(phone)
}