正常使用:
import {debounce} from "lodash";
import { fetch } from 'xxxx';
export default {
// ...
methods: {
remoteMethod: debounce(function (value = "") {
const params = {
keywords: value,
};
fetch(params)
.then((res) => {
// ...
})
}, 350, ),
},
}
这样写的话就会有一个问题:
这种方法对于被重用的组件来说是有问题的,因为这个预置防抖的函数是 有状态的:它在运行时维护着一个内部状态。他们共享一个函数,那么它们之间将会互相影响。
那么如何解决这个问题呢?
Vue的文档中也给出了相应的解决方案。
export default {
created() {
// 每个实例都有了自己的预置防抖的处理函数
this.debouncedClick = _.debounce(this.click, 500)
},
unmounted() {
// 最好是在组件卸载时
// 清除掉防抖计时器
this.debouncedClick.cancel()
},
methods: {
click() {
// ... 对点击的响应 ...
}
}
}