lodash-es 工具库常用工具函数和案例详解

一、概述

Lodash中文文档

Lodash 是一个一致性、模块化、高性能的 JavaScript 实用工具库,算是从 Underscore 分离出来的超集。

Lodash 通过降低 array、number、objects、string 等等的使用难度从而让 JavaScript 变得更简单。Lodash 的模块化方法 非常适用于:

  • 遍历 array、object 和 string
  • 对值进行操作和检测
  • 创建符合功能的函数

lodash 为了良好的浏览器兼容性,它使用了旧版 es5 的模块语法;而lodash-es则使用了 es6 的模块语法,这让 webpack 之类的打包工具可以对其进行tree shake (摇树优化)以删除未使用的代码来优化打包体积。所以在使用lodash库时,推荐通过lodash-es来进行导入操作。

注:tree-shaking(摇树优化)的作用:移除上下文中未引用的代码(dead code)。

数字化管理平台
Vue3+Vite+VueRouter+Pinia+Axios+ElementPlus
Vue权限系统案例
个人博客

二、安装及使用

2.1 安装

安装 lodash-es

npm i lodash-es

引入 lodash-es 中的函数

import { shuffle, cloneDeep, throttle, debounce } from 'lodash-es'

2.2 浅拷贝 clone

_.clone(value) 创建一个 value 的浅拷贝。返回拷贝后的值。

var objects = [{ 'a': 1 }, { 'b': 2 }];
 
var shallow = _.clone(objects);
console.log(shallow[0] === objects[0]);  // true

2.3 深拷贝 cloneDeep

_.cloneDeep(value) 类似 _.clone 但是它会递归拷贝 value。返回拷贝后的值。

var objects = [{ 'a': 1 }, { 'b': 2 }];
var deep = _.cloneDeep(objects);
console.log(deep[0] === objects[0]); // false

2.4 防抖 debounce

_.debounce(func, [wait=0], [options=]) 创建一个 debounced(防抖动)函数,该函数会从上一次被调用后,延迟 wait 毫秒后调用 func 方法。 返回新的 debounced(防抖动)函数。

参数

  1. func (Function): 要防抖动的函数。
  2. [wait=0] (number): 需要延迟的毫秒数。
  3. [options=] (Object): 选项对象。
  4. [options.leading=false] (boolean): 指定在延迟开始前调用。
  5. [options.maxWait] (number): 设置 func 允许被延迟的最大值。
  6. [options.trailing=true] (boolean): 指定在延迟结束后调用。
// 避免窗口在变动时出现昂贵的计算开销。
jQuery(window).on('resize', _.debounce(calculateLayout, 150));
 
// 当点击时 `sendMail` 随后就被调用。
jQuery(element).on('click', _.debounce(sendMail, 300, {
  'leading': true,
  'trailing': false
}));
 
// 确保 `batchLog` 调用1次之后,1秒内会被触发。
var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });
var source = new EventSource('/stream');
jQuery(source).on('message', debounced);
 
// 取消一个 trailing 的防抖动调用
jQuery(window).on('popstate', debounced.cancel);

2.5 节流 throttle

_.throttle(func, [wait=0], [options=]) 创建一个节流函数,在 wait 秒内最多执行 func 一次的函数。 返回节流的函数。

参数:

  1. func (Function): 要节流的函数。
  2. [wait=0] (number): 需要节流的毫秒。
  3. [options=] (Object): 选项对象。
  4. [options.leading=true] (boolean): 指定调用在节流开始前。
  5. [options.trailing=true] (boolean): 指定调用在节流结束后。
// 避免在滚动时过分的更新定位
jQuery(window).on('scroll', _.throttle(updatePosition, 100));
 
// 点击后就调用 `renewToken`,但5分钟内超过1次。
var throttled = _.throttle(renewToken, 300000, { 'trailing': false });
jQuery(element).on('click', throttled);
 
// 取消一个 trailing 的节流调用。
jQuery(window).on('popstate', throttled.cancel);

2.6 打乱值 shuffle

_.shuffle(collection) 创建一个被打乱值的集合。返回打乱的新数组。

参数collection (Array|Object): 要打乱的集合

_.shuffle([1, 2, 3, 4]);
// => [4, 1, 3, 2]

三、Vue 动画案例

<transition-group> 组件还有一个特殊之处。除了进入和离开,它还可以为定位的改变添加动画。只需了解新增的 v-move 类就可以使用这个新功能,它会应用在元素改变定位的过程中。像之前的类名一样,它的前缀可以通过 name attribute 来自定义,也可以通过 move-class attribute 手动设置

如下代码,是一个九宫格的布局,利用 lodash 中的 shuffle 随机打乱其顺序,然后通过 move 属性实现过渡效果,非常炫酷:

页面演示效果:
在这里插入图片描述
示例代码:

<template>
   <TransitionGroup name="list" tag="ul" class="list" leave-active-class="animate__animated animate__bounce"
        enter-active-class="animate__animated animate__flipInY">
        <li v-for="item in list" :key="item.id">{
   
   { item.number }}</li>
    </TransitionGroup>
</template>
  
<script setup>
import { shuffle } from 'lodash-es'
import HTransition from './HTransition.vue';
import { ref } from 'vue'
let isShow = ref(false)

const list = ref(Array.apply(null, { length: 90 }).map((_, index) => {
    return {
        id: index,
        number: (index % 9) + 1
    }
}))

const confuse = () => {
    list.value = shuffle(list.value)
}
</script>
  
<style scoped lang="less">
.list {
    width: 270px;
    display: flex;
    flex-wrap: wrap;
    background-color: orange;
    position: relative;
}

li {
    width: 30px;
    height: 30px;
    line-height: 30px;
    text-align: center;
    list-style: none;
    border: solid 1px #e7e7e7;
}

.list-move {
    transition: transform 0.8s ease;
}
</style>

猜你喜欢

转载自blog.csdn.net/qq_39335404/article/details/129951010#comments_27096214