先在工具类定义防抖函数 utils/common.js
/**
* 防抖函数,let fun = debounce(callback, 1000) 再运行fun(),这样使用
* @param {*} callback 方法
* @param {*} wait 延迟时间
* @example
* @return
*
*/
function debounce(callback, wait) {
let timer
return function (arg) {
clearTimeout(timer)
timer = setTimeout(function () {
callback(arg)
}, wait)
}
}
在vue中的应用
<script>
import utils from "@/utils/common"
export default {
data() {
return {
screenWidth: null,
resetGraph: null
}
},
watch: {
screenWidth: {
handler: function (newval, oldval) {
if (newval == null || oldval == null) return
this.resetGraph()
},
immediate: true,
deep: true
},
},
mounted() {
this.init()
},
methods: {
init() {
this.resetGraph = utils.debounce(this.resizeFun, 1000)
this.screenWidth = document.body.clientWidth
window.onresize = () => {
return (() => {
this.screenWidth = document.body.clientWidth
})()
}
},
resizeFun() {
console.log('防抖测试')
//业务函数
this.graph()
}
}
}
</script>