• requestAnimationFrame实现vue虚拟滚动插件


    如何渲染几万条数据并不卡住界面

    这道题考察了如何在不卡住页面的情况下渲染数据,也就是说不能一次性将几万条都渲染出来,而应该一次渲染部分 DOM,那么就可以通过 requestAnimationFrame 来每 16 ms 刷新一次

    DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>Documenttitle>
    head>
    <body>
      <ul>控件ul>
      <script>
        setTimeout(() => {
          // 插入十万条数据
          const total = 100000
          // 一次插入 20 条,如果觉得性能不好就减少
          const once = 20
          // 渲染数据总共需要几次
          const loopCount = total / once
          let countOfRender = 0
          let ul = document.querySelector("ul");
          function add() {
            // 优化性能,插入不会造成回流
            const fragment = document.createDocumentFragment();
            for (let i = 0; i < once; i++) {
              const li = document.createElement("li");
              li.innerText = Math.floor(Math.random() * total);
              fragment.appendChild(li);
            }
            ul.appendChild(fragment);
            countOfRender += 1;
            loop();
          }
          function loop() {
            if (countOfRender < loopCount) {
              window.requestAnimationFrame(add);
            }
          }
          loop();
        }, 0);
      script>
    body>
    html>
    
    • 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
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42

    使用js实现一个持续的动画效果

    //兼容性处理
    window.requestAnimFrame = (function(){
        return window.requestAnimationFrame       ||
               window.webkitRequestAnimationFrame ||
               window.mozRequestAnimationFrame    ||
               function(callback){
                    window.setTimeout(callback, 1000 / 60);
               };
    })();
    
    var e = document.getElementById("e");
    var flag = true;
    var left = 0;
    
    function render() {
        left == 0 ? flag = true : left == 100 ? flag = false : '';
        flag ? e.style.left = ` ${left++}px` :
            e.style.left = ` ${left--}px`;
    }
    
    (function animloop() {
        render();
        requestAnimFrame(animloop);
    })();
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    打基础

    <template>
    	<div>
    		<button v-on="{click:fn}">点击按钮</button> // 在这里给dom绑定了原生的click
    		// 当点击按钮 在控制台会打印出 11111
    	</div>
    </template>
    
    
    // 在methods内声明的函数
    fn(){
        console.log(11111);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    实现vue虚拟滚动插件

    VirtualBlock.vue

    <template>
        <div v-on="pageMode ? {} : {scroll: handleScroll}" :style="containerStyle" ref="vb">
            <div :style="{height: `${offsetTop}px`}"></div>
            <div v-for="item in renderList" 
                 :style="{height: `${fixedBlockHeight ? fixedBlockHeight : item.height}px`}" 
                 :key="`${item.id}`">
                <slot :data="item"></slot>
            </div>
            <div :style="{height: `${offsetBot}px`}"></div>
        </div>
    </template>
    
    <script>
    export default {
        props: {
            data: {
                type: Array,
                required: true
            },
            height: {
                type: Number
            },
            fixedBlockHeight: {
                type: Number
            },
            pageMode: {
                type: Boolean,
                default: true
            }
        },
        data() {
            return {
                viewportBegin: 0,
                viewportEnd: this.height,
                offsetTop: 0,
                offsetBot: 0,
                renderList: [],
                transformedData: []
            }
        },
        watch: {
            data: {
                handler: function(newVal, oldVal) {
                    this.computeTransformedData(newVal);
                    if (oldVal) {
                        this.$nextTick(
                            () => {
                                this.$refs.vb.scrollTop = 0;
                                this.handleScroll();
                            }
                        );
                    }
                },
                immediate: true
            },
            pageMode(newVal) {
                if (newVal) {
                    window.addEventListener('scroll', this.handleScroll);
                } else {
                    window.removeEventListener('scroll', this.handleScroll);
                }
                this.computeTransformedData(this.data);
                this.$nextTick(
                    () => {
                        this.$refs.vb.scrollTop = 0;
                        this.handleScroll()
                    }
                );
            },
            fixedBlockHeight() {
                this.handleScroll();
            }
        },
        mounted() {
            if (this.pageMode) {
                window.addEventListener('scroll', this.handleScroll);
                this.computeTransformedData(this.data);
            }
            this.updateVb(0);
        },
        destroyed() {
            if (this.pageMode) {
                window.removeEventListener('scroll', this.handleScroll);
            }
        },
        methods: {
            computeTransformedData(oriArr) {
                if (!this.fixedRowHeight && ((this.pageMode && this.$refs.vb) || !this.pageMode)) {
                    let curHeight = this.pageMode ? this.$refs.vb.offsetTop : 0;
                    let rt = [curHeight];
                    oriArr.forEach(
                        item => {
                            curHeight += item.height;
                            rt.push(curHeight);
                        }
                    );
                    this.transformedData = rt;
                }
            },
            handleScroll() {
                const scrollTop = this.pageMode ? window.scrollY : this.$refs.vb.scrollTop;
                window.requestAnimationFrame(
                    () => {
                        this.updateVb(scrollTop);
                    }
                );
            },
            binarySearchLowerBound(s, arr) {
                let lo = 0;
                let hi = arr.length - 1;
                let mid;
                while(lo <= hi) {
                    mid = ~~((hi + lo) / 2);
                    if (arr[mid] > s) {
                        if (mid === 0) {
                            return 0;
                        } else {
                            hi = mid - 1;
                        }
                    } else if (arr[mid] < s) {
                        if (mid + 1 < arr.length) {
                            if (arr[mid + 1] > s) {
                                return mid;
                            } else {
                                lo = mid + 1;
                            }
                        } else {
                            return -1;
                        }
                    } else {
                        return mid;
                    }
                }
            },
            binarySearchUpperBound(e, arr) {
                let lo = 0;
                let hi = arr.length - 1;
                let mid;
                while(lo <= hi) {
                    mid = ~~((hi + lo) / 2);
                    if (arr[mid] > e) {
                        if (mid > 0) {
                            if (arr[mid - 1] < e) {
                                return mid;
                            } else {
                                // normal flow
                                hi = mid - 1;
                            }
                        } else {
                            return -1;
                        }
                    } else if (arr[mid] < e) {
                        if (mid === arr.length - 1) {
                            return arr.length - 1;
                        } else {
                            lo = mid + 1;
                        }
                    } else {
                        return mid;
                    }
                }
            },
            fixedBlockHeightLowerBound(s, fixedBlockHeight) {
                const sAdjusted = this.pageMode ? s - this.$refs.vb.offsetTop : s;
                const computedStartIndex = ~~(sAdjusted / fixedBlockHeight);
                return computedStartIndex >= 0 ? computedStartIndex : 0;
            },
            fixedBlockHeightUpperBound(e, fixedBlockHeight) {
                const eAdjusted = this.pageMode ? e - this.$refs.vb.offsetTop : e;
                const compuedEndIndex = Math.ceil(eAdjusted / fixedBlockHeight);
                return compuedEndIndex <= this.data.length ? compuedEndIndex : this.data.length;
            },
            findBlocksInViewport(s, e, heightArr, blockArr) {
                var vbOffset = this.pageMode ? this.$refs.vb.offsetTop : 0;
                const lo = this.fixedBlockHeight ? 
                            this.fixedBlockHeightLowerBound(s, this.fixedBlockHeight) :
                            this.binarySearchLowerBound(s, heightArr);
                const hi = this.fixedBlockHeight ? 
                            this.fixedBlockHeightUpperBound(e, this.fixedBlockHeight) :
                            this.binarySearchUpperBound(e, heightArr);
    
                if(this.fixedBlockHeight) {
                    this.offsetTop = lo >= 0 ? lo * this.fixedBlockHeight : 0;
                    this.offsetBot = hi >= 0 ? (blockArr.length - hi ) * this.fixedBlockHeight : 0;
                } else {
                    this.offsetTop = lo >= 0 ? heightArr[lo] - vbOffset : 0;
                    this.offsetBot = hi >= 0 ? heightArr[heightArr.length - 1] - heightArr[hi] : 0;
                }
                return blockArr.slice(lo, hi);
            },
            updateVb(scrollTop) {
                const viewportHeight = this.pageMode ? window.innerHeight : this.height;
                this.viewportBegin = scrollTop;
                this.viewportEnd = scrollTop + viewportHeight;
                this.renderList = this.findBlocksInViewport(this.viewportBegin, this.viewportEnd, this.transformedData, this.data);
            }
        },
        computed: {
            containerStyle() {
                return {
                    ...(!this.pageMode && {height: `${this.height}px`}),
                    ...(!this.pageMode && {'overflow-y' : 'scroll'})
                }
            }
        }
    }
    </script>
    
    • 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
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207

    在App.vue内使用

    <template>
        <div>
            <select v-model="dataAmt">
                <option value="100">100</option>
                <option value="1000">1000</option>
                <option value="10000">10000</option>
            </select>
            <input type="checkbox" v-model="isPageMode">
            <input type="checkbox" v-model="isFixedHeight">
    
            <VirtualBlock :fixedBlockHeight="isFixedHeight ? 50 : undefined"  :pageMode="isPageMode" :height="500" :data="data" ref="vb">
                <template slot-scope="{data}">
                    <div :style="{height: '100%', 'background-color': data.color}">
                        {{data.id}}
                    </div>
                </template>
            </VirtualBlock>
        </div>
    </template>
    
    <script>
    export default {
        name: "App",
        data() {
            return {
                dataAmt: '1000',
                isPageMode: false,
                data: [],
                isFixedHeight: true
            }
        },
        created() {
            this.data = this.dataConstructor(this.dataAmt, this.isFixedHeight);
        },
        watch: {
            dataAmt: function() {
                this.data = this.dataConstructor(this.dataAmt, this.isFixedHeight);
            },
            isFixedHeight: function() {
                this.data = this.dataConstructor(this.dataAmt, this.isFixedHeight);
            }
        },
        methods: {
            dataConstructor(amount, fixedHeight) {
                let arr = [];
                for (let i = 0 ; i < Number(amount) ; i++) {
                    let obj = {};
                    obj['height'] = fixedHeight ? 50 : this.randomInteger(30, 90);
                    obj['id'] = i;
                    obj['color'] = '#' + this.randomColor();
                    arr.push(obj);
                }
                return arr;
            },
            randomColor() {
                return Math.floor(Math.random() * 16777215).toString(16);
            },
            randomInteger(min, max) {
                return Math.floor(Math.random() * (max - min + 1) ) + min;
            }
        }
    }
    </script>
    
    • 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
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
  • 相关阅读:
    【Xcode-宏定义配置】
    LeetCode每日一题——Maximum Sum With Exactly K Elements
    离散Fréchet算法
    845. 八数码(Acwing)
    Jetpack Compose 的简单 MVI 框架
    物联网_00_物理网介绍
    Python 存储数据到数据库
    信息学奥赛一本通 1368:对称二叉树(tree_c)
    python实现层次分析法(AHP)
    PCL 生成空间三角形面点云
  • 原文地址:https://blog.csdn.net/formylovetm/article/details/125885965