一、安装
cnpm i lodash -S
二、方法一
1、引入
import _ from 'lodash'
Vue.prototype._ = _
2、使用
this._.debounce(this.handleClick,1000,false)//防抖
二、方法二
1、引入
let _ = require('lodash')
2、使用
_.debounce(this.handleClick,1000,false)
例子:
_.chunk(array, [size=1])
/*将数组(array)拆分成多个 size 长度的区块,并将这些区块组成一个新数组。 如果array 无法被分割成全部等长的区块,那么最后剩余的元素将组成一个区块。*/
//array (Array)需要处理的数组
//[size=1] (number)每个数组区块的长度
_.chunk(['a', 'b', 'c', 'd'], 2);
// => [['a', 'b'], ['c', 'd']]
_.chunk(['a', 'b', 'c', 'd'], 3);
// => [['a', 'b', 'c'], ['d']]
三、vue单文件组件中使用
这里写的debounce函数和Lodash中的debounce函数,效果一样!
<template>
<div>
<el-button @click="myDebounce">我的debounce</el-button>
<el-button @click="_debounce">lodash的debounce</el-button>
</div>
</template>
<script>
import {
debounce } from '@/utils/util'
let _ = require('lodash')
export default {
methods: {
handleClick1() {
console.log(`真正执行的函数,次数比较少:handleClick1.....`)
},
handleClick2() {
console.log(`真正执行的函数,次数比较少:handleClick2.....`)
},
myDebounce() {
console.log(`myDebounce.....`)
this.DB()
},
_debounce() {
console.log(`_debounce.....`)
this._DB()
}
},
created() {
this.DB = debounce(this.handleClick1, 1000, false)
this._DB = this._.debounce(this.handleClick2,1000,false)
}
}
</script>
更多函数操作请看:Lodash函数库