先来上图
这是两个测试vue渲染速度的页面,源码如下
<template>
<div>
<h1>{{ mm }}</h1>
<h1>{{ nn }}</h1>
<h1>{{ time }} s</h1>
<button @click="sum">点击</button>
</div>
</template>
<script>
export default {
data() {
return {
mm: 321,
nn: 123,
time: 0,
};
},
methods: {
// sum() {
// let start, end
// start = window.performance.now()
// var a = new Array(10000000)
// a.fill(1)
// a.forEach(item => {
// this.mm += 1
// this.nn += 1
// })
// this.$nextTick(() => {
// end = window.performance.now()
// this.time = (end - start) / 1000
// })
// },
sum() {
let start, end;
start = window.performance.now();
let { mm, nn } = JSON.parse(JSON.stringify(this.$data));
var a = new Array(10000000);
a.fill(1);
a.forEach((item) => {
mm += 1;
nn += 1;
});
Object.assign(this, { mm, nn });
this.$nextTick(() => {
end = window.performance.now();
this.time = (end - start) / 1000;
});
},
},
};
</script>
<style scoped>
</style>
可以知道,第二次的渲染时间只要0.1s,相比第一次提升巨大,推荐大家采用第二种写法哦! 优化了下,用JSON.parse(JSON.stringify())先深拷贝下data,然后就算是对象也是可以解除vue的响应式的,速度基本不受影响!