gpt4 book ai didi

javascript - 如何使用 Svelte 去抖动/节流?

转载 作者:数据小太阳 更新时间:2023-10-29 05:09:19 28 4
gpt4 key购买 nike

所以我现在有:

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,不如将 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.

关于javascript - 如何使用 Svelte 去抖动/节流?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46104897/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com