这道题考察了如何在不卡住页面的情况下渲染数据,也就是说不能一次性将几万条都渲染出来,而应该一次渲染部分 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>
//兼容性处理
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);
})();
<template>
<div>
<button v-on="{click:fn}">点击按钮</button> // 在这里给dom绑定了原生的click
// 当点击按钮 在控制台会打印出 11111
</div>
</template>
// 在methods内声明的函数
fn(){
console.log(11111);
}
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>
在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>