如何用Svelte去抖/踩油门?

Dan*_*ble 8 javascript svelte

所以我目前有:

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>
Run Code Online (Sandbox Code Playgroud)

并得到错误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))
}
Run Code Online (Sandbox Code Playgroud)

Ric*_*ris 10

这是应该被去抖的方法本身 - 所以不要调用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>
Run Code Online (Sandbox Code Playgroud)

这里简化了REPL示例.

  • 是否有关于如何在 Svelte 3 中执行此操作的更新示例?由于语法发生了巨大的变化,我很挣扎 (2认同)
  • @TheHanna https://svelte.dev/repl/32550061c28f49169bc7a6d3a21dedd0?version=3 (2认同)