vue里的节流、防抖

 

防抖(debounce)

解释:持续触发某事件时,一定间隔内没有再触发事件,间隔过后事件处理函数才会执行。

以防止用户或浏览器触发事件过于频繁,减少浏览器负担。

 

节流(throttle)

解释:当持续触发事件时,以规定间隔执行一次或多次事件处理函数。

与防抖不同,节流不会停下,而是有间隔的触发事件函数。

 

常用的应用场景:

用户页面的点击按钮,比如登陆、注册、验证等;

页面频繁计算时;

监听页面滚动;

监听用户输入。

 

小案例:

<!DOCTYPE html>
<html>
    <head>
        <meta charset='utf-8'>
        <title></title>
        <script type='text/javascript' src='../vue.js'></script>
        <style type="text/css">
            #app {
                height: 2000px;
            }
        </style>
    </head>
    <body>
        <div id='app'>
            <button type="button" @click='btn()' :disabled="isDisabled">刷新</button>
            {{isDisabled}}
        </div>

        <script type='text/javascript'>
            new Vue({
                el: '#app',
                data() {
                    return {
                        isDisabled: false
                    }
                },
                methods: {
                    
                    // 防抖
                    btn() {
                        this.isDisabled = true
                        setTimeout(() => {
                            this.isDisabled = false
                        }, 1000)
                    },
                    
                    // 防抖
                    debounce(fn, delay) {
                        let timer = null
                        return function() {
                            if (timer)
                                clearTimeout(timer)
                            timer = setTimeout(fn, delay)
                        }
                    },
                    showTop() {
                        let scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
                        console.log('滚动条位置:' + scrollTop)
                    },

                    // 节流
                    throttle(fn, delay) {
                        let valid = true
                        return function() {
                            if (!valid) return false

                            valid = false
                            setTimeout(() => {
                                fn()
                                valid = true
                            }, delay)
                        }
                    },
                    showTop() {
                        let scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
                        console.log('滚动条位置' + scrollTop)
                    }
                },
                mounted() {
                    // window.onscroll = this.debounce(this.showTop, 800)
                    window.onscroll = this.throttle(this.showTop, 2000)
                }
            })
        </script>
    </body>
</html>

 

posted @ 2020-12-08 11:19  浮云共我归  阅读(444)  评论(0)    收藏  举报