所以我现在有:
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))
}发布于 2017-09-08 00:33:44
应该取消的是方法本身-因此,与其对每个输入事件调用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>编辑: svelte v3版本
<input on:input={handleInput}>
<script>
import debounce from 'lodash/debounce'
let name = '';
const handleInput = debounce(e => {
name = e.target.value;
}, 300)
</script>发布于 2020-01-05 20:08:26
接受的答案对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>https://stackoverflow.com/questions/46104897
复制相似问题