// utils.js
// 防抖函数
export function debounce(func, delay) {
let timer;
return function() {
const context = this;
const args = arguments;
clearTimeout(timer);
timer = setTimeout(() => {
func.apply(context, args);
}, delay);
};
}
// 节流函数
export function throttle(func, delay) {
let lastTime = 0;
return function() {
const context = this;
const args = arguments;
const now = new Date().getTime();
if (now - lastTime >= delay) {
func.apply(context, args);
lastTime = now;
}
};
}
在main.js中挂载到 Vue 原型:
import Vue from 'vue';
import { debounce, throttle } from './utils';
// 将防抖函数挂载到Vue原型
Vue.prototype.$debounce = debounce;
// 将节流函数挂载到Vue原型
Vue.prototype.$throttle = throttle;
import App from './App.vue';
Vue.config.productionTip = false;
new Vue({
render: h => h(App),
}).$mount('#app');
在 Vue 组件中使用:
<template>
<div>
<input type="text" @input="handleInput">
<button @click="handleClick">点击</button>
</div>
</template>
<script>
export default {
methods: {
handleInput() {
// 使用防抖函数
this.$debounce(this.doSearch, 500)();
},
doSearch() {
console.log('执行搜索操作');
},
handleClick() {
// 使用节流函数
this.$throttle(this.doSomething, 1000)();
},
doSomething() {
console.log('执行一些操作');
}
}
};
</script>
掌握JavaScript节流与防抖技术
769

被折叠的 条评论
为什么被折叠?



