vue2 窗口缩放配合防抖函数使用

  1. 先在工具类定义防抖函数 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)
    }
}
  1. 在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>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值