笔记本项目的标题和内容在输入修改时就会触发@input="updateNote",我在函数里面发送请求,保存数据,但是如果每输入一个字就发送请求是不合理的,所以就封装了一个节流组件,使用时直接调用
在 src/helpers/common.js
export default {//节流函数
debounce(fn, delay = 500) { //默认500毫秒
let timer = null
return function() {
let args = arguments;
if(timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
fn.apply(this, args); // this 指向vue
}, delay);
};
}
}
调用:
import Common from '@/helpers/common.js';
methods: {
updateNote: Common.debounce(function () {//不能用箭头函数,因为没有this
Notes.updateNote({noteId: this.curNotes.id},
{title: this.curNotes.title, content: this.curNotes.content})
.then(res => {
this.statusText = '已保存'
}).catch(res => {
this.statusText = '保存出错'
})
}, 600),