【问题标题】:Using throttle with Vue 3在 Vue 3 中使用节流阀
【发布时间】:2021-12-10 18:36:27
【问题描述】:

我在 Vue 3 项目中使用 lodash,当我尝试在 setup 函数中使用 _.throttle 时,它不起作用。我在stackblitz写了一个demo。

<template>
  <div id="app">
    <button @click="handleClick">Click</button>
  </div>
</template>

<script>
import _ from 'lodash';

export default {
  name: 'App',
  setup() {
    const handleClick = () =>
      _.throttle(function () {
        console.log('hi');
      }, 2000);

    return {
      handleClick,
    };
  },
};
</script>

【问题讨论】:

    标签: vue.js lodash vuejs3 vue-composition-api


    【解决方案1】:

    您缺少通过添加 () 来运行节流功能:

      const handleClick = () =>
          _.throttle(function () {
            console.log('hi');
          }, 2000)();
    
    

    或将其分配给变量然后运行它:

      const handleClick = () =>{
         let throttled= _.throttle(function () {
            console.log('hi');
          }, 2000);
         
         throttled();
       }
    
    

    【讨论】:

      【解决方案2】:

      好的,我现在有一个解决方案。我的同伴说省略() =&gt; 可以修复它,添加{ trailing: false }更好。

      const handleClick = _.throttle(function () { console.log('hi'); }, 2000, { trailing: false });

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-01-22
        • 2012-05-11
        • 2020-08-02
        • 1970-01-01
        • 2019-10-03
        • 2018-10-23
        • 2017-03-22
        • 2019-07-07
        相关资源
        最近更新 更多