- 焦点聚焦
import Vue from 'vue'
// 插件对象(必须有 install 方法, 才可以注入到 Vue.use 中)
export default {
install () {
Vue.directive('fofo', {
inserted (el) {
el = el.querySelector('input')
el.focus()
}
})
}
}
- 格式化日期格式
export const formatDate = (time) => {
// 将xxxx-xx-xx的时间格式,转换为 xxxx/xx/xx的格式
return time.replace(/\-/g, "/");
}
- 是否在数组内
export const inArray = (search, array) => {
for (var i in array) {
if (array[i] == search) return true
}
return false
}
- 日期转换
export const dateFormat = (fmt, date) => {
const opt = {
"Y+": date.getFullYear().toString(), // 年
"m+": (date.getMonth() + 1).toString(), // 月
"d+": date.getDate().toString(), // 日
"H+": date.getHours().toString(), // 时
"M+": date.getMinutes().toString(), // 分
"S+": date.getSeconds().toString() // 秒
// 有其他格式化字符需求可以继续添加,必须转化成字符串
};
let ret
for (let k in opt) {
ret = new RegExp("(" + k + ")").exec(fmt)
if (ret) {
fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
};
};
return fmt
}
dateFormat('YYYY-mm-dd HH:MM:SS', new Date()) ==> 2020-01-01 08:00:00
- 判断是否为空对象
export const isEmptyObject = (object) => {
return Object.keys(object).length === 0
}
- 判断是否为对象
export const isObject = (object) => {
return Object.prototype.toString.call(object) === '[object Object]'
}
- 判断是否为数组
export const isArray = (array) => {
return Object.prototype.toString.call(array) === '[object Array]'
}
- 判断是否为空
export const isEmpty = (value) => {
if (isArray(value)) {
return value.length === 0
}
if (isObject(value)) {
return isEmptyObject(value)
}
return !value
}
- 对象深拷贝
export const cloneObj = (obj) => {
let newObj = obj.constructor === Array ? [] : {};
if (typeof obj !== 'object') {
return;
}
for (let i in obj) {
newObj[i] = typeof obj[i] === 'object' ? cloneObj(obj[i]) : obj[i];
}
return newObj
}
- 节流函数
export function throttle(fn, delay = 100) {
// 首先设定一个变量,在没有执行我们的定时器时为null
var timer = null
return function() {
// 当我们发现这个定时器存在时,则表示定时器已经在运行中,需要返回
if (timer) return
timer = setTimeout(() => {
fn.apply(this, arguments)
timer = null
}, delay)
}
- 防抖函数
export function debounce(fn, delay) {
let timer
return function() {
const that = this
const _args = arguments // 存一下传入的参数
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(function() {
fn.apply(that, _args)
}, delay)
}
}