我在Vue模板中有一个简单的输入框,我想或多或少地使用下面这样的选项:
<input type="text" v-model="filterKey" debounce="500">但是,debounce属性是在Vue 2中被否决。建议只说:“使用v-on:input +第三方退出函数”。
您如何正确地实现它?
我尝试过使用lodash、v-on:input和v-model来实现它,但是我想知道没有额外的变量是否可以实现。
模板中的:
<input type="text" v-on:input="debounceInput" v-model="searchInput">脚本中的:
data: function () {
return {
searchInput: '',
filterKey: ''
}
},
methods: {
debounceInput: _.debounce(function () {
this.filterKey = this.searchInput;
}, 500)
}过滤键随后将在computed道具中使用。
发布于 2017-02-13 10:11:45
我使用的是脱去 NPM包,实现方式如下:
<input @input="debounceInput">methods: {
debounceInput: debounce(function (e) {
this.$store.dispatch('updateInput', e.target.value)
}, config.debouncers.default)
}使用房客和问题中的示例,实现如下所示:
<input v-on:input="debounceInput">methods: {
debounceInput: _.debounce(function (e) {
this.filterKey = e.target.value;
}, 500)
}发布于 2018-11-26 17:21:17
选项1:可重复使用,没有deps
/helpers.js
export function debounce (fn, delay) {
var timeoutID = null
return function () {
clearTimeout(timeoutID)
var args = arguments
var that = this
timeoutID = setTimeout(function () {
fn.apply(that, args)
}, delay)
}
}/Component.vue
<script>
import {debounce} from './helpers'
export default {
data () {
return {
input: '',
debouncedInput: ''
}
},
watch: {
input: debounce(function (newVal) {
this.debouncedInput = newVal
}, 500)
}
}
</script>选项2:组件内,也没有deps
/Component.vue
<template>
<input type="text" v-model="input" />
</template>
<script>
export default {
data: {
timeout: null,
debouncedInput: ''
},
computed: {
input: {
get() {
return this.debouncedInput
},
set(val) {
if (this.timeout) clearTimeout(this.timeout)
this.timeout = setTimeout(() => {
this.debouncedInput = val
}, 300)
}
}
}
}
</script>发布于 2018-04-11 16:38:42
在methods中分配退出可能会带来麻烦。所以,不是这样的:
// Bad
methods: {
foo: _.debounce(function(){}, 1000)
}你可以尝试:
// Good
created () {
this.foo = _.debounce(function(){}, 1000);
}如果有一个组件的多个实例,这将成为一个问题--类似于data应该是返回一个对象的函数的方式。如果每个实例被认为是独立的,那么它们都需要自己的退出函数。
下面是这个问题的一个例子:
Vue.component('counter', {
template: '<div>{{ i }}</div>',
data: function(){
return { i: 0 };
},
methods: {
// DON'T DO THIS
increment: _.debounce(function(){
this.i += 1;
}, 1000)
}
});
new Vue({
el: '#app',
mounted () {
this.$refs.counter1.increment();
this.$refs.counter2.increment();
}
});<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>
<div id="app">
<div>Both should change from 0 to 1:</div>
<counter ref="counter1"></counter>
<counter ref="counter2"></counter>
</div>
https://stackoverflow.com/questions/42199956
复制相似问题