1.在入口文件main.js中:
//防抖函数
export let debounce = (() => {
let instances = []
return function (fun, delay = 300) {
//项目中,多个地方用到防抖,进行判断,每次调用全局的防抖函数,是否是同一块代码
const stackLines = new Error().stack.split('\n');
let callerLine = stackLines[2];
//判断数组中是否有了
let index = instances.findIndex(item => {
return item.callerLine == callerLine
})
if (index < 0) {
//没有的话,直接新增一个
instances.push({ callerLine, fun, delay, timer: null })
index = instances.length - 1
} else {
//有了的话,直接将传递的逻辑函数赋值进去
instances[index].fun = fun
}
//找到数据中对应的对象
let instance = instances[index]
let ctx = this
let args = arguments
//有时间间隔器,则清除
if (instance.timer) {
clearTimeout(instance.timer)
}
//进行其他逻辑
instance.timer = setTimeout(() => {
instance.timer = null
instance.fun.apply(ctx, args)
}, instance.delay)
}
})()
//节流函数
export let throttle = (() => {
let instances = []
return function (fun, delay = 300) {
const stackLines = new Error().stack.split('\n');
let callerLine = stackLines[2];
let index = instances.findIndex(item => {
return item.callerLine == callerLine
})
if (index < 0) {
instances.push({ callerLine, fun, delay, timeout: null })
index = instances.length - 1
} else {
instances[index].fun = fun
}
let instance = instances[index]
let args = arguments;//注意如果要传参的话 这句不能省略
if (!instance.timeout) {
instance.timeout = setTimeout(() => {
instance.timeout = null;
instance.fun.apply(this, args)
}, instance.delay)
}
}
})()
Vue.prototype.$debounce = debounce;
Vue.prototype.$throttle = throttle;
2.页面中使用:
<div id="watch-example">
<p>
问一个是否的问题:
<input v-model="question2">
</p>
<p>{{ answer2 }}</p>
</div>
data() {
return {
question2: '',
answer2: '请输入问题,否则我无法回答你!'
};
},
watch: {
question2: function (newQuestion, oldQuestion) {
this.answer2 = '请等待!';
this.$debounce(this.getAnswer2, 1000);
}
},
getAnswer2: function() {
if (this.question.indexOf('?') === -1) {
this.answer2 = '请输入疑问句!';
return;
}else{
this.answer2 = '请稍后...';
setTimeout(() => {
this.answer2 = '章总';
}, 1000)
}
}