如果Vue是把AK,那么Lodash就是子弹
如果Vue是把AK,那么Lodash就是子弹……
1. 序言
做Vue项目肯定离不开各种工具库函数和方法的封装使用,有时候与其自己写方法造轮子,不如发扬下拿来主义,简单高效的完成开发工作。当然用的时候要明白其实现原理。接下来我就推荐一个特别好用的工具库,它就是lodash.
2. Lodash
Lodash 是一个一致性、模块化、高性能的 JavaScript 实用工具库。提供了丰富的函数和方法,满足大部分开发需要。通过脚手架构建的Vue项目本身就已经安装了Lodash工具库,可以直接使用。如果没有就需要自己引入。具体安装方法就不多做叙述,有需要可以看Lodash官网或者Lodash中文文档网。
Lodash官网: lodash.com/
Lodash 中文文档: https://www.lodashjs.com/
3. 使用
使用首先引入Lodash到当前页面,引入方式import _ from 'lodash'
或者import { xx } from 'lodash'
。然后要用到那个方法就_.xx
或者 xx()
直接调用即可。下面就拿debounce
举个例子,其他方法使用类似,举一反三就行。
<template>
<div
class="edit-input"
:style="{'font-size':fontSize}"
v-html="innerText"
:contenteditable="isEdit"
@focus="isLock = true"
@blur="onBlur"
@input="changeText"
>
</div>
</template>
<script>
import _ from 'lodash'
//或者
//import { debounce } from 'lodash'
export default {
methods: {
// 调用_.debounce()或者 debounce()
// 使用注意:
//debounce第一个参数不能写成箭头函数
changeText:_.debounce(function(e){
this.$emit('input',e.target.innerText);
}, 500)
}
}
</script>
复制代码
4.结尾
Lodash虽然好用,无须自己造轮子,但是有时间最好还是去看看源码,学习一下各种方法实现的原理也是一种进步。