Vue 使用“虚拟列表”解决 SKU 过多造成的渲染问题

在生成 SKU 后由于数量过多,在生成 SKU 和数据修改上都存在加载慢的问题,可以使用虚拟列表的方式解决,只渲染可视区域的列表元素,提高加载速度。

组件代码:

/**
 * 虚拟列表组件
 */
let VirtualList = {
    props: {
        // 要渲染的数据
        data: {type: Array, default: []},
        // 高度
        height: {type: Number, default: 200},
        // 每条数据渲染的节点的高度
        rowHeight: {type: Number, default: 30}
    },
    data() {
        return {
            offset: 0,
            offsetIndex: 0
        }
    },
    computed: {
        boxHeight() {
            return this.data.length * this.rowHeight;
        },
        offsetData() {
            let count = Math.ceil(this.height / this.rowHeight);
            let index = Math.floor(this.offset / this.rowHeight);
            this.offsetIndex = index;
            return this.data.slice(index, count + index);
        }
    },
    mounted() {
        let that = this
        this.$refs.box.addEventListener('scroll', function () {
            that.offset = that.$refs.box.scrollTop;
        }, false)

    },
    template: `
    <div ref="box" class="vl-box newupdatevl-box scroll_cont" :style="{ height: height + 'px' }">
        <div :style="{ height: boxHeight + 'px' }" style="border-radius: 10px;">
            <div class="vl-box-item" :style="{
                    height: rowHeight + 'px',
                    lineHeight: rowHeight + 'px',
                    top: (index + offsetIndex) * rowHeight + 'px'
                }" v-for="(item,index) in offsetData" :key="item.key">
                <slot :item="item"></slot>
             </div>
        </div>
    </div>`
}

使用组件:

<virtual-list :data="skus" :height="tableHeight" :rowheight="76">
    <template v-slot="slotProps">
        <tr>
            <td v-for="(it, ix) in slotProps.item.spec" :key="ix">{{it.name}}</td>
            <td>{{slotProps.item.stock}}</td>
            <td>{{slotProps.item.price}}></td>
        </tr>
    </template>
</virtual-list>

了解 王坤的博客 的更多信息

订阅后即可通过电子邮件收到最新文章。

作者:kenney wang
暂无评论

发送评论 编辑评论


				
上一篇
下一篇

了解 王坤的博客 的更多信息

立即订阅以继续阅读并访问完整档案。

继续阅读