添加resize事件
1.在鈎子函數mounted中為window添加resize事件
window.addEventListener('resize', this.pageResize,true)
2.在鈎子函數methods中添加resize處理方法
pageResize: debounce(function(){
let that = this;
that.$nextTick(()=>{
let bodyHeight = document.body.clientHeight;
let navbarHeight = document.querySelector(".navbar").clientHeight;
let tagHeight = document.querySelector(".tags-view-wrapper").clientHeight;
let elCard = document.querySelector(".searchCard").offsetHeight;
that.tableHeight = bodyHeight - (navbarHeight + tagHeight + elCard) - 16;
})
},200),
移除resize事件
1.在鈎子函數beforeDestroy中移除resize事件
window.removeEventListener('resize',this.pageResize,true)
注意點
resize移除事件失效的原因:
- 添加事件、移除事件使用的方法格式不一樣
例如:添加用的window.onresize = function(){}
,移除用的window.removeEventListener('resize')
-
如果使用了debounce防抖,不要將debounce放到addEventListener的方法里,直接放在處理函數里
例如:
window.addEventListener('resize', debounce(this.pageResize,200),true)
移除失效,需要將debounce()
放在this.pageResize
方法里面
debounce防抖
/**
* @param {Function} func
* @param {number} wait
* @param {boolean} immediate
* @return {*}
*/
export function debounce(func, wait, immediate) {
let timeout, args, context, timestamp, result
const later = function() {
// 據上一次觸發時間間隔
const last = +new Date() - timestamp
// 上次被包裝函數被調用時間間隔 last 小於設定時間間隔 wait
if (last < wait && last > 0) {
timeout = setTimeout(later, wait - last)
} else {
timeout = null
// 如果設定為immediate===true,因為開始邊界已經調用過了此處無需調用
if (!immediate) {
result = func.apply(context, args)
if (!timeout) context = args = null
}
}
}
return function(...args) {
context = this
timestamp = +new Date()
const callNow = immediate && !timeout
// 如果延時不存在,重新設定延時
if (!timeout) timeout = setTimeout(later, wait)
if (callNow) {
result = func.apply(context, args)
context = args = null
}
return result
}
}