美文网首页react & vue & angularlodash
在 Vue 中使用lodash对事件进行防抖和节流

在 Vue 中使用lodash对事件进行防抖和节流

作者: 莫伊剑客 | 来源:发表于2022-01-07 16:55 被阅读0次

Vue 里使用 lodash 中的 Debouncing 和 Throttling

事件节流和防抖是提高性能或降低网络开销的好方法。虽然 Vue 1曾经支持对事件的节流和防抖,但是在Vue 2中为了保持核心的简单性,删除对事件的节流和防抖的支持。因此,在Vue 2对对事件进行防抖和节流我们可以使用 lodash 来做。

安装

可以通过 yarn 或 npm 安装 lodash。

# Yarn
$ yarn add lodash
# NPM
$ npm install lodash --save

注意:如果我们不想导入lodash的所有内容,而只导入所需的部分,则可以通过一些Webpack构建自定义来解决问题。还可以使用lodash.throttle和lodash.debounce等软件包分别安装和导入lodash的各个部分。

throttling 方法

要对事件进行节流处理方法非常简单,只需将要调用的函数包装在lodash的_.throttle函数中即可。

<template>
  <button @click="throttledMethod()">Click me as fast as you can!</button>
</template>
 
<script>
import _ from 'lodash'
 
export default {
  methods: {
    throttledMethod: _.throttle(function() {
      console.log('I get fired every two seconds!')
    }, 2000)
  }
}
</script>

debouncing 方法

尽管节流在某些情况下很有用,但一般情况我们经常使用的是防抖。防抖实质上将我们的事件分组在一起,并防止它们被频繁触发。要在Vue组件中使用节流,只需将要调用的函数包装在lodash的_.debounce函数中。

<template>
  <button @click="throttledMethod()">Click me as fast as you can!</button>
</template>
 
<script>
import _ from 'lodash'
 
export default {
  methods: {
    throttledMethod: _.debounce(function() {
      console.log('I only get fired once every two seconds, max!')
    }, 2000)
  }
}
</script>

注意 throttling 和debouncing 回调函数使用function(){},这样内部才可以正常调用vue的this,否则会报undefined

相关文章

网友评论

    本文标题:在 Vue 中使用lodash对事件进行防抖和节流

    本文链接:https://www.haomeiwen.com/subject/uuijcrtx.html