vue 项目涉及的焦点聚焦、格式化日期、判断是否为对象或数组、判断是否为空、深拷贝、节流、防抖

  • 焦点聚焦
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)
  }
}
  • 9
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值