我在 Vue 模板中有一个简单的输入框,我想或多或少地像这样使用 debounce:
<input type="text" v-model="filterKey" debounce="500">
但是 debounce
属性是 deprecated in Vue 2。建议只说:“使用 v-on:input + 3rd 方去抖功能”。
您如何正确实施它?
我尝试使用 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)
}
filterkey 稍后会在 computed
道具中使用。
我正在使用 debounce NPM 包并像这样实现:
<input @input="debounceInput">
methods: {
debounceInput: debounce(function (e) {
this.$store.dispatch('updateInput', e.target.value)
}, config.debouncers.default)
}
使用 lodash 和问题中的示例,实现如下所示:
<input v-on:input="debounceInput">
methods: {
debounceInput: _.debounce(function (e) {
this.filterKey = e.target.value;
}, 500)
}
选项 1:可重用,无依赖
如果在您的项目中多次需要,建议使用
/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)
}
}
/组件.vue
<script>
import {debounce} from './helpers'
export default {
data () {
return {
input: '',
debouncedInput: ''
}
},
watch: {
input: debounce(function (newVal) {
this.debouncedInput = newVal
}, 500)
}
}
</script>
选项 2:组件内,也没有部门
建议使用一次或在小型项目中使用
/组件.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>
[Vue warn]: Error in callback for watcher "input": "TypeError: Cannot read property 'call' of undefined"
在 methods
中分配去抖动可能会很麻烦。所以代替这个:
// Bad
methods: {
foo: _.debounce(function(){}, 1000)
}
你可以试试:
// Good
created () {
this.foo = _.debounce(function(){}, 1000);
}
如果您有一个组件的多个实例,这将成为一个问题 - 类似于 data
应该是一个返回对象的函数的方式。如果每个实例应该独立运行,它们都需要自己的去抖动功能。
这是问题的一个例子:
Vue.component('counter', { template: '
data()
即可。
没有lodash非常简单
handleScroll: function() {
if (this.timeout)
clearTimeout(this.timeout);
this.timeout = setTimeout(() => {
// your action
}, 200); // delay
}
destroyed() { clearInterval(this.timeout) }
也是一件好事。
我遇到了同样的问题,这是一个无需插件即可工作的解决方案。
由于 <input v-model="xxxx">
与
<input
v-bind:value="xxxx"
v-on:input="xxxx = $event.target.value"
>
我想我可以在 xxxx = $event.target.value
中对 xxxx 的分配设置一个去抖动功能
像这样
<input
v-bind:value="xxxx"
v-on:input="debounceSearch($event.target.value)"
>
方法:
debounceSearch(val){
if(search_timeout) clearTimeout(search_timeout);
var that=this;
search_timeout = setTimeout(function() {
that.xxxx = val;
}, 400);
},
@input="update_something"
操作,则在 that.xxx = val
that.update_something();
之后调用它
debounceSearch: function(val) { if (this.search_timeout) clearTimeout(this.search_timeout); var that=this; this.search_timeout = setTimeout(function() { that.thread_count = val; that.update_something(); }, 500); },
如果您需要一种非常简约的方法,我制作了一个(最初从 vuejs-tips 派生,也支持 IE),可在此处获得:https://www.npmjs.com/package/v-debounce
用法:
<input v-model.lazy="term" v-debounce="delay" placeholder="Search for something" />
然后在您的组件中:
<script>
export default {
name: 'example',
data () {
return {
delay: 1000,
term: '',
}
},
watch: {
term () {
// Do something with search term after it debounced
console.log(`Search term changed to ${this.term}`)
}
},
directives: {
debounce
}
}
</script>
请注意,我在接受的答案之前发布了这个答案。这是不正确的。这只是问题解决方案的一步。我已经编辑了接受的问题,以显示作者的实现和我使用的最终实现。
根据评论和 linked migration document,我对代码进行了一些更改:
在模板中:
<input type="text" v-on:input="debounceInput" v-model="searchInput">
在脚本中:
watch: {
searchInput: function () {
this.debounceInput();
}
},
设置过滤键的方法保持不变:
methods: {
debounceInput: _.debounce(function () {
this.filterKey = this.searchInput;
}, 500)
}
这看起来少了一个调用(只有 v-model
,而不是 v-on:input
)。
debounceInput()
两次吗? v-on:
将检测输入变化并调用 debounce,并且由于模型已绑定,searchInput 的 watch 函数也会调用 debounceInput
...对吗?
如果您需要使用 lodash 的 debounce
函数应用动态延迟:
props: {
delay: String
},
data: () => ({
search: null
}),
created () {
this.valueChanged = debounce(function (event) {
// Here you have access to `this`
this.makeAPIrequest(event.target.value)
}.bind(this), this.delay)
},
methods: {
makeAPIrequest (newVal) {
// ...
}
}
和模板:
<template>
//...
<input type="text" v-model="search" @input="valueChanged" />
//...
</template>
注意: 在上面的示例中,我制作了一个搜索输入示例,它可以使用 props
中提供的自定义延迟调用 API
尽管这里几乎所有的答案都是正确的,但如果有人正在寻找快速解决方案,我对此有一个指令。 https://www.npmjs.com/package/vue-lazy-input
它适用于@input 和 v-model,支持自定义组件和 DOM 元素,去抖动和节流。
Vue.use(VueLazyInput) new Vue({ el: '#app', data() { return { val: 42 } }, 方法:{ onLazyInput(e){ console.log(e.target.value) } } } )
要创建去抖动方法,您可以使用计算方法,这样它们就不会在组件的多个实例之间共享:
<template>
<input @input="handleInputDebounced">
<template>
<script>
import debounce from 'lodash.debouce';
export default {
props: {
timeout: {
type: Number,
default: 200,
},
},
methods: {
handleInput(event) {
// input handling logic
},
},
computed: {
handleInputDebounced() {
return debounce(this.handleInput, this.timeout);
},
},
}
</script>
您也可以使其与不受控制的 v-model
一起使用:
<template>
<input v-model="debouncedModel">
<template>
<script>
import debounce from 'lodash.debouce';
export default {
props: {
value: String,
timeout: {
type: Number,
default: 200,
},
},
methods: {
updateValue(value) {
this.$emit('input', value);
},
},
computed: {
updateValueDebounced() {
return debounce(this.updateValue, this.timeout);
},
debouncedModel: {
get() { return this.value; },
set(value) { this.updateValueDebounced(value); }
},
},
}
</script>
如果您使用的是 Vue,您也可以使用 v.model.lazy
而不是 debounce
,但请记住 v.model.lazy
并不总是有效,因为 Vue 将其限制为自定义组件。
对于自定义组件,您应该使用 :value
和 @change.native
<b-input :value="data" @change.native="data = $event.target.value" ></b-input>
1 使用箭头函数的短版本,具有默认延迟值
文件:debounce.js 在 ex: ( import debounce from '../../utils/debounce' )
export default function (callback, delay=300) {
let timeout = null
return (...args) => {
clearTimeout(timeout)
const context = this
timeout = setTimeout(() => callback.apply(context, args), delay)
}
}
2 混合选项
文件:debounceMixin.js
export default {
methods: {
debounce(func, delay=300) {
let debounceTimer;
return function() {
// console.log("debouncing call..");
const context = this;
const args = arguments;
clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => func.apply(context, args), delay);
// console.log("..done");
};
}
}
};
在 vueComponent 中使用:
<script>
import debounceMixin from "../mixins/debounceMixin";
export default {
mixins: [debounceMixin],
data() {
return {
isUserIdValid: false,
};
},
mounted() {
this.isUserIdValid = this.debounce(this.checkUserIdValid, 1000);
},
methods: {
isUserIdValid(id){
// logic
}
}
</script>
另一种选择,例如
我能够通过很少的实现来使用 debounce。
我正在使用带有 boostrap-vue 的 Vue 2.6.14:
将此 pkg 添加到您的 package.json:https://www.npmjs.com/package/debounce
将此添加到 main.js:
import { debounce } from "debounce";
Vue.use(debounce);
在我的组件中,我有这个输入:
<b-form-input
debounce="600"
@update="search()"
trim
id="username"
v-model="form.userName"
type="text"
placeholder="Enter username"
required
>
</b-form-input>
它所做的只是调用 search() 方法,并且 search 方法使用 form.userName 来执行搜索。
如果您可以将 debounce 函数的执行移到某个类方法中,则可以使用 utils-decorators 库 (npm install --save utils-decorators
) 中的装饰器:
import {debounce} from 'utils-decorators';
class SomeService {
@debounce(500)
getData(params) {
}
}
public debChannel = debounce((key) => this.remoteMethodChannelName(key), 200)
vue-property-decorator
不定期副业成功案例分享
data
中添加v-model=your_input_variable
。因此,您不依赖e.target
,而是使用 Vue,因此您可以访问this.your_input_variable
而不是e.target.value
this
。