前端常用utils工具方法小总结

前端常用utils工具方法小总结

// 数组去重
const uniqueArray = arr => [...new Set(arr)];

// 从url获取参数,并且转换成对象
const getParameters = URL => JSON.parse(`{"${decodeURI(URL.split("?")[1]).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"')}"}`)

//检查对象是否为空
const isEmpty = obj => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object
//检查是否为对象
const isObject = obj => !(Object.keys(obj).length === 0)

//字符串反转
const reverseString = str => str.split('').reverse().join('')

//随机生成十六进制颜色值
const randomHexColor = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, '0')}`

//检查当前选项卡是否在后台
const isTabActive = () => !document.hidden;

//检查元素是否处于焦点
const eleIsInFocus = el => (el.document.activeElement)

//检查设备类型
const judgeDeviceType = () => /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|OperaMini/i.test(navigator.userAgent) ? 'Mobile' : 'PC';

//文字复制到剪切板
const copyText = async text => await navigator.clipboard.writeText(text)

// 返回选中的内容
const getSelectedText = () => window.getSelection().toString();

//查询某天是否为工作日
const isWeekday = (date) => date.getDay() % 6 !== 0;

//两日期之间相差的天数
const dayDiff = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000);

//检查日期是否有效
const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf());

// 计算两个日期之间的间隔
const dayDif = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000)

//查找日期位于一年中的第几天
const dayOfYear = (date) => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);

//时间格式化
const timeFromDate = date => date.toTimeString().slice(0, 8);

//字符串首字母大小
const firstUpper = str => str.charAt(0).toUpperCase() + str.slice(1);

//随机字符串
const randomString = () => Math.random().toString(36).slice(2)

//去除字符串中的html
const striphtml = html => html(new DOMParser().parseFromString(html, 'text/html').body.textContent || '')

//判断数组是否为空
const isNotEmpty = array => Array.isArray(array) && array.length > 0

//合并两个数组
const merge = (a, b) => a.concat(b)
const mergeArr = (a, b) => [...a, ...b]

//获取一组数据的平均值
const average = (...args) => args.reduce((a, b) => a + b) / args.length

//取两个整数之间的随机值
const randomNumber = (min, max) => Math.floor(Math.random() * (max - min + 1) + min)

//指定位数的四舍五入
const roundNumber = (n, d) => Number(Math.round(n + "e" + d) + 'e-' + d)

//将RGB转化为十六机制
const rgbaToHex = (r, g, b, a) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)

//清除所以cookie
const clearCookies = document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date(0).toUTCString()};path=/`));

//检测是否是黑暗模式
const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches

//滚动到顶部
const goToTop = () => window.screenTop(0, 0)

//判断是否滚动到底部
const scrolledToBottom = () => document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight;

//重定向到一个url
const redirectToUrl = (url) => window.location.href = url

//打开浏览器的打印页面
const showPrintDialog = () => window.print()

//随机布尔值
const randomBoolean = () => Math.random() >= 0.5

//变量交换
let a = 1, b = 2;
[a, b] = [b, a]

//获取变量的类型
const trueTypeOf = (obj) => Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();


防抖

定义:n 秒内只运行一次,若在 n 秒内重复触发,只有一次生效

//处理任务,和等待时间
function debounce(fn, delay){
     let timerId = null
     return function(){
         const context = this
         //如果接到订单就再等3分钟
         if(timerId){window.clearTimeout(timerId)}
         //3分钟没有接到订单就直接配送
         timerId = setTimeout(()=>{
             fn.apply(context, arguments)
             timerId = null
         },delay)
     }
 }

节流

定义:n 秒后在执行该事件,若在 n 秒内被重复触发,则重新计时

节流就是指连续触发事件但是在 n 秒中只执行一次函数。节流会稀释函数的执行频率

export const debouncer = (fn, time, interval = 200) => {
	if (time - (window.debounceTimestamp || 0) > interval) {
		fn && fn();
		window.debounceTimestamp = time;
	}
}
function throttle(fn, delay){
     // 设置一个触发开关
     let canUse = true
     return function(){
     //如果为true,就触发技能,否则就不能触发
         if(canUse){
             fn.apply(this, arguments)
             //触发技能后,关闭开关
             canUse = false
             //在3秒后打开开关
             setTimeout(()=>canUse = true, delay)
         }
     }
 }

cookie工具方法

设置cookie

function setCookieItem(sKey, sValue, vEnd, sPath, sDomain, bSecure) {
    if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) {
        return false;
    }
    var sExpires = "";
    if (vEnd) {
        switch (vEnd.constructor) {
            case Number:
                sExpires = vEnd === Infinity 
                    ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" 
                	: "; max-age=" + vEnd;
                break;
            case String:
                sExpires = "; expires=" + vEnd;
                break;
            case Date:
                sExpires = "; expires=" + vEnd.toUTCString();
                break;
        }
    }
    document.cookie = encodeURIComponent(sKey) 
        + "=" + encodeURIComponent(sValue) 
        + sExpires 
        + (sDomain ? "; domain=" + sDomain : "") 
        + (sPath ? "; path=" + sPath : "") 
        + (bSecure ? "; secure" : "");
    return true;
}

判断cookie是否存在

function isCookieItemExisted(sKey) {
    return new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[-.+*]/g, "\\$&") + "\\s*\\=").test(document.cookie);
}

删除cookie

function removeCookieItem(sKey, sPath, sDomain) {
    if (!sKey || !isCookieItemExisted(sKey)) {
        return false;
    }
    document.cookie = encodeURIComponent(sKey) 
        + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" 
        + (sDomain ? "; domain=" + sDomain : "") 
        + (sPath ? "; path=" + sPath : "");
    return true;
}

查找cookie

function getCookieByKey(sKey) {
    return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[-.+*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
  },

localhostStorage工具方法

设置localStorage

export const setStore = (params = {}) => {
    let {
        name,
        content,
        type,
    } = params;
    name = keyName + name
    let obj = {
        dataType: typeof (content),
        content: content,
        type: type,
        datetime: new Date().getTime()
    }
    if (type) window.sessionStorage.setItem(name, JSON.stringify(obj));
    else window.localStorage.setItem(name, JSON.stringify(obj));
}

获取localStorage

export const getStore = (params = {}) => {
    let {
        name,
        debug
    } = params;
    name = keyName + name
    let obj = {},
        content;
    obj = window.sessionStorage.getItem(name);
    if (validatenull(obj)) obj = window.localStorage.getItem(name);
    if (validatenull(obj)) return;
    try {
        obj = JSON.parse(obj);
    } catch {
        return obj;
    }
    if (debug) {
        return obj;
    }
    if (obj.dataType == 'string') {
        content = obj.content;
    } else if (obj.dataType == 'number') {
        content = Number(obj.content);
    } else if (obj.dataType == 'boolean') {
        content = eval(obj.content);
    } else if (obj.dataType == 'object') {
        content = obj.content;
    }
    return content;
}

删除localStorage

export const removeStore = (params = {}) => {
    let {
        name,
        type
    } = params;
    name = keyName + name
    if (type) {
        window.sessionStorage.removeItem(name);
    } else {
        window.localStorage.removeItem(name);
    }
}

获取全部local Storage

export const getAllStore = (params = {}) => {
    let list = [];
    let {
        type
    } = params;
    if (type) {
        for (let i = 0; i <= window.sessionStorage.length; i++) {
            list.push({
                name: window.sessionStorage.key(i),
                content: getStore({
                    name: window.sessionStorage.key(i),
                    type: 'session'
                })
            })
        }
    } else {
        for (let i = 0; i <= window.localStorage.length; i++) {
            list.push({
                name: window.localStorage.key(i),
                content: getStore({
                    name: window.localStorage.key(i),
                })
            })
        }
    }
    return list;
}

清空全部local Storage

export const clearStore = (params = {}) => {
    let {
        type
    } = params;
    if (type) {
        window.sessionStorage.clear();
    } else {
        window.localStorage.clear()
    }
}

时间转换

    function getdate(date) {
        var now = new Date(date),
            y = now.getFullYear(),
            m = now.getMonth() + 1,
            d = now.getDate();
        return y + '-' + (m < 10 ? '0' + m : m) + '-' + (d < 10 ? '0' + d : d) + ' ' + now.toTimeString().substr(0, 8);
    }
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: 基于 Vue 的前端工具非常丰富,下面列举了一些比较流行的: 1. Vue CLI:官方提供的脚手架工具,能够快速创建 Vue 项目,并提供了许多插件和特性,如 Babel、TypeScript、ESLint、单元测试、代码分割等等。 2. Vuex:官方提供的状态管理库,用于解决组件间共享数据的问题,也提供了一些工具函数帮助你更好地管理状态。 3. Vue Router:官方提供的路由库,用于管理前端路由,支持嵌套路由、动态路由、路由守卫等特性。 4. Vuetify:一款基于 Material Design 的 Vue 组件库,提供了丰富的 UI 组件和样式,能够快速搭建美观的界面。 5. Element:一款基于 Vue 2.0 的组件库,提供了一些常用的 UI 组件,如按钮、表单、对话框等等。 6. Ant Design Vue:一款基于 Ant Design 的 Vue 组件库,提供了一些高质量的 UI 组件,能够快速搭建美观的界面。 7. Vue Test Utils:官方提供的测试工具,能够方便地编写单元测试和集成测试。 8. Vue Devtools:浏览器插件,能够方便地调试 Vue 应用程序。 以上仅是部分常见的工具,实际上还有很多其他的工具和库,如 Nuxt.js、VuePress、VueFire、Vue-i18n 等等。 ### 回答2: 基于Vue的前端工具有很多,以下是一些常用工具: 1. Vue CLI:Vue官方提供的脚手架工具,可以快速搭建基于Vue的项目结构,提供了项目初始化、开发调试、构建打包等功能,方便快捷地进行Vue项目开发。 2. Vue Devtools:Vue开发工具,是一款Chrome浏览器扩展插件,能够在浏览器中调试Vue应用,查看组件层级结构、数据状态、事件等,提供了便利的调试功能。 3. Vue Router:Vue官方提供的路由管理工具,用于构建单页应用(SPA),通过路由配置实现页面之间的跳转和状态管理,方便用户进行页面间的导航和数据传递。 4. Vuex:Vue官方提供的状态管理工具,用于集中管理Vue应用中的共享状态,通过定义状态、派发和监听状态的变化,实现不同组件之间的数据共享,方便应用的扩展和维护。 5. Element UI:一款基于Vue的桌面端UI组件库,提供了一套美观、易用的UI组件,包括按钮、表单、弹窗等常用组件,可以快速搭建漂亮的前端界面。 6. Vuetify:一款基于Vue的响应式UI框架,提供了丰富的组件和布局系统,实现了Material Design风格,并且支持主题定制,方便开发者创建美观的用户界面。 以上是一些基于Vue的前端工具,它们可以提高开发效率、优化用户体验,并且丰富了Vue开发者的工具箱,为项目的开发和调试提供了便利。 ### 回答3: 基于Vue的前端工具有很多,以下是其中几个常用工具: 1. Vue CLI:Vue CLI是一个官方提供的脚手架工具,可以快速搭建Vue项目的基础架构,包括项目配置、Webpack配置等。它还提供了一些插件和命令,方便开发者进行项目的构建、打包、测试等工作。 2. Vue Devtools:Vue Devtools是一个用于Vue调试的浏览器插件,可以通过它来查看Vue组件的层级关系、数据状态、事件等,方便开发者进行调试和性能优化。 3. Vue Router:Vue Router是Vue官方提供的路由管理器,用于实现前端路由的功能。它可以帮助开发者将不同的页面组织成不同的路由,实现页面之间的切换和跳转。 4. Vuex:Vuex是Vue官方推荐的状态管理工具,用于在Vue应用中集中管理和共享状态。通过Vuex,开发者可以将应用中的数据保存在一个全局存储空间中,并通过一些规则来修改和获取这些数据。 5. Element UI:Element UI是一套基于Vue的UI组件库,提供了丰富的UI组件,包括表单、弹框、导航、菜单等,方便开发者快速构建符合设计规范的界面。 6. Vue Test Utils:Vue Test Utils是Vue官方提供的测试工具库,用于编写和运行Vue组件的单元测试。它提供了一些API和工具函数,帮助开发者编写可靠和高效的测试用例。 除了上述的工具之外,还有许多第三方的Vue工具和插件可供选择,开发者可以根据自己的需求选择和使用。这些工具和插件都可以提高开发效率、简化开发流程,使得基于Vue的前端开发更加轻松和便捷。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

前端少年汪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值