【问题标题】:How to debounce / throttle with Svelte?如何使用 Svelte 去抖动/节流?
【发布时间】:2018-02-16 16:43:03
【问题描述】:

所以我目前有:

App.html

<div>
  <input on:input="debounce(handleInput, 300)">
</div>

<script>
  import { debounce } from 'lodash'

  export default {
    data () {
      name: ''
    },

    methods: {
      debounce,
      async handleInput (event) {
        this.set({ name: await apiCall(event.target.value).response.name })
      }
    }
  }
</script>

并得到错误Uncaught TypeError: Expected a function at App.debounce。这来自 Lodash,因此似乎没有通过 Svelte 的方法。

额外的额外编辑

关于我目前如何实现它的额外背景:

oncreate () {
  const debounceFnc = this.handleInput.bind(this)

  this.refs.search.addEventListener('input', debounce(debounceFnc, 300))
}

【问题讨论】:

  • 你能详细说明你想要做什么吗?您通常不会在组件上使用 debounce 方法 — 相反,您的方法之一会被去抖动
  • @RichHarris 抱歉 Rich 我的示例似乎错过了我添加的模板部分。添加了更多上下文以显示我也想要实现的目标。
  • 尝试使用import debounce from 'lodash/debounce'
  • 同样的错误@OluwafemiSule。我进一步编辑了额外的上下文,以展示我目前是如何实现这一目标的。我只是想知道我是否可以在模板中以“Svelte”的方式做到这一点。
  • debounce 是在组件上定义的方法,所以它应该用作this.debounce(debounceFnc, 300)

标签: javascript svelte


【解决方案1】:

应该去抖动的是方法本身——所以不要在每个输入事件上调用debounce,而是将handleInput设置为去抖动方法:

<div>
  <input on:input="handleInput(event)">
</div>

<script>
  import { debounce } from 'lodash'

  export default {
    data () {
      return { name: '' };
    },

    methods: {
      handleInput: debounce (async function (event) {
        this.set({ name: await apiCall(event.target.value).response.name })
      }, 300)
    }
  }
</script>

Simplified REPL example here.

编辑:svelte v3 版本

<input on:input={handleInput}>

<script>
  import debounce from 'lodash/debounce'

  let name = '';

  const handleInput = debounce(e => {
    name = e.target.value;
  }, 300)
</script>

REPL example here.

【讨论】:

  • 不知道您可以从 REPL 中的 lodash 导入。谢谢,里奇!
  • 是否有更新示例说明如何在 Svelte 3 中执行此操作?由于语法发生了如此巨大的变化,我一直在苦苦挣扎
  • @TheHanna 我假设你已经解决了,但我已经更新了答案。为您所做的所有工作而欢呼 Rich。
【解决方案2】:

接受的答案对 Svelte v1 有效。对于 v3,您可以使用以下代码实现相同的目的:

<input placeholder='edit me' bind:this={input}>
<p>name: {name}</p>

<script>
  import { onMount } from "svelte"
    import { debounce } from 'lodash-es'
    var name="", input;
    onMount(()=>{
        input.addEventListener('input', debounce((e)=>{name=e.target.value}, 250))
    })
</script>

【讨论】:

  • 你不应该为此使用 ref 使用 on:input 指令:)
猜你喜欢
  • 2021-07-09
  • 2015-07-25
  • 2019-11-11
  • 2019-07-07
  • 2021-08-19
  • 2012-07-13
  • 2016-05-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多