Detailed explanation of common tool functions and cases of lodash-es tool library

I. Overview

Lodash Chinese documentation

Lodash is a consistent, modular, high-performance JavaScript utility library that is a superset separated from Underscore .

Lodash makes JavaScript easier by making it easier to use arrays, numbers, objects, strings, and more. Lodash’s modular approach is great for:

  • Traverse array, object and string
  • Manipulate and test values
  • Create functions that fit the functionality

lodashFor good browser compatibility, it uses the module syntax of the old version of es5; instead, lodash-esit uses the module syntax of es6, which allows packaging tools such as webpack to perform tree shake(tree-shaking optimization) on it to remove unused code. Optimize packaging volume. Therefore, when using lodashthe library, it is recommended lodash-esto perform the import operation through.

Note: The role of tree-shaking (tree-shaking optimization): remove unreferenced code (dead code) in the context.

Digital management platform
Vue3+Vite+VueRouter+Pinia+Axios+ElementPlus
Vue permission system case
personal blog

2. Installation and use

2.1 Installation

Install lodash-es

npm i lodash-es

Introduce functions in lodash-es

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

2.2 Shallow copy clone

_.clone(value) Create a valueshallow copy of . Returns the copied value.

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

2.3 Deep copy cloneDeep

_.cloneDeep(value) Similar to _.clonebut it copies recursively value. Returns the copied value.

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

2.4 Anti-shake debounce

_.debounce(func, [wait=0], [options=])Create a debounced function that will waitcall functhe method after a delay of milliseconds from the last time it was called. Returns the new debounced function.

Parameters :

  1. func (Function) : The function to be anti-shake.
  2. [wait=0] (number) : The number of milliseconds to delay.
  3. [options=] (Object) : Options object.
  4. [options.leading=false] (boolean) : Specifies to be called before the delay starts.
  5. [options.maxWait] (number) : Set functhe maximum value allowed to be delayed.
  6. [options.trailing=true] (boolean) : Specifies to be called after the delay has elapsed.
// 避免窗口在变动时出现昂贵的计算开销。
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=])funcCreate a throttling function that executes at most once in wait seconds . Function that returns throttling.

parameter:

  1. func (Function) : The function to throttle.
  2. [wait=0] (number) : milliseconds to throttle.
  3. [options=] (Object) : Options object.
  4. [options.leading=true] (boolean) : Specifies to call before throttling begins.
  5. [options.trailing=true] (boolean) : Specifies that the call should be called after throttling ends.
// 避免在滚动时过分的更新定位
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 value shuffle

_.shuffle(collection)Creates a collection of shuffled values. Returns a new scrambled array.

Parameters : collection (Array|Object) : the collection to be scrambled

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

3. Vue animation case

<transition-group> There is another special thing about components. In addition to entering and leaving, it can also animate positioning changes. You only need to understand the new v-move class to use this new feature, which will be applied when elements change positioning. Like the previous class name, its prefix can be customized through the name attribute or manually set through the move-class attribute

The following code is a nine-square grid layout. It uses shuffle in lodash to randomly disorder its order, and then uses the move attribute to achieve a transition effect. It is very cool:

Page demonstration effect:
Insert image description here
sample code:

<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>

Guess you like

Origin blog.csdn.net/qq_39335404/article/details/129951010#comments_27096214