Lodash 初学指南(适用于 Vue 3)
Lodash 初学指南(适用于 Vue 3)
Lodash 是一个流行的 JavaScript 实用工具库,提供了大量高效、模块化的函数,适用于数组、对象、字符串等数据类型的操作。在 Vue 3 中,Lodash 可以显著简化复杂逻辑的编写。
1. 安装与引入
安装
npm install lodash # 完整版
npm install lodash-es # ES Modules 版本(推荐 Vue 3 使用)
按需引入(推荐)
import { throttle, debounce, cloneDeep, truncate } from 'lodash-es';
或使用完整引入(不推荐,体积较大)
import _ from 'lodash';
2. 常用 Lodash 方法(Vue 3 场景)
(1)字符串处理
_.truncate
- 截断字符串
import { truncate } from 'lodash-es';const longText = '这是一段非常长的文本,需要截断显示';
const shortText = truncate(longText, {length: 10, // 最大长度omission: '...', // 省略符号
});console.log(shortText); // "这是一段非常..."
_.startCase
/_.camelCase
- 格式化字符串
_.startCase('hello world'); // "Hello World"
_.camelCase('hello world'); // "helloWorld"
(2)数组操作
_.chunk
- 数组分块
const arr = [1, 2, 3, 4, 5];
_.chunk(arr, 2)</