一坏晦、安裝
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)
三喇澡、vue單文件組件中使用
里面分別有我自己寫的debounce函數(shù)和lodash的debounce函數(shù)浦马,效果一樣时呀!
<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(`真正執(zhí)行的函數(shù),次數(shù)比較少:handleClick1.....`)
},
handleClick2() {
console.log(`真正執(zhí)行的函數(shù)晶默,次數(shù)比較少: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>
debounce測(cè)試.png
注意:以前我是在data選項(xiàng)里面定義
DB:null
谨娜,然后再methods里面初始化函數(shù),但是需要判斷‘如果有了就不賦函數(shù)磺陡,如果為空就賦’趴梢,發(fā)現(xiàn)比較麻煩;后來直接在created鉤子里面定義币他,就很方便了坞靶!