这是今天面试时被点拨的一点,自定义指令封装节流防抖函数
非自定义指令版节流
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| export const debounce = function (fn, delay) { let timer = null let immediate = true return function () { const _this = this if (immediate) { fn.apply(_this) immediate = false } else { clearTimeout(timer) timer = setTimeout(function () { fn.apply(_this) }, delay); }
} }
import { debounce } from '../utils/debounce'
methods: { test: debounce(function () { this.count++ }, 1000), }
|
自定义指令节流
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| import Vue from 'vue'
Vue.directive('debounce', { inserted(el, binding) { let { fn, event = "click", delay = 800 } = binding.value; let timer = null; let immediate = true el.addEventListener(event, function () { if (immediate) { fn() immediate = false } else { clearTimeout(timer) timer = setTimeout(function () { fn() }, delay) }
}) } })
import "@/directive/debounce"
<button v-debounce="{ fn: test, delay: 1000 }">click</button>
|
非自定义指令版防抖
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| export const throttle = function (fn, delay) { let timer = null; return function () { const _this = this if (!timer) { timer = setTimeout(function () { fn.apply(_this) timer = null; }, delay); } } }
|
自定义指令版防抖
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| import Vue from 'vue'
Vue.directive('throttle', { inserted(el, binding) { let { fn, event = "click", delay = 800 } = binding.value; let timerB = null; let flag = true el.addEventListener(event, () => { if (flag) { flag = false fn.apply(this, arguments); timerB = setTimeout(() => { flag = true clearTimeout(timerB); timerB = null }, delay); } }); }, });
|