文章目錄
- 代碼實現
- 單頁面引入
- 全局引入
- 使用
代碼實現
const debounce = (fn: any, delay: number) => {let timer: any = undefined;return (item: any) => {if (timer) clearTimeout(timer);timer = setTimeout(() => fn(item), delay);}
};export default debounce;
單頁面引入
// 防抖(單頁面引用)
import debounce from '../../../utils/debounce';
全局引入
main.ts
import App from './App.vue';
import debounce from './utils/debounce';const app = createApp(App);
app.config.globalProperties.$debounce = debounce;
使用
html
<el-slider v-model="sliderValue" size="small" show-input @input="handleScheduleInput" />
單頁面使用
let handleScheduleInput = debounce((val: number) => {console.log('滑塊: ', val);
}, 1000 * 1);
全局使用
// 防抖(全局掛載)
let self = getCurrentInstance()?.appContext.config.globalProperties;let handleScheduleInput = self?.$debounce((val: number) => {console.log('滑塊: ', val);
}, 2000 * 1);