使用performance开启性能追踪
1 | if (process.env.NODE_ENV !== 'production') { |
- 是开发环境的时候开启
- 开启后我们可以下载 Vue Performance Devtool 这一 chrome 插件来看查看各个组件的加载情况
使用errorHandler 来捕获异常
1
2
3
4
5
6
7
8
9Vue.config.errorHandler = function (err, vm, info) {
let {
message, // 异常信息
name, // 异常名称
stack // 异常堆栈信息
} = err;
// vm 为抛出异常的 Vue 实例
// info 为 Vue 特定的错误信息,比如错误所在的生命周期钩子
} - 在入口文件中加入上述代码后,我们便可以捕获到 Vue 项目中的一些异常信息了,但是需要注意的是 Vue 2.4.0 起的版本才支持捕获 Vue 自定义事件处理函数内部的错误
使用nextTick将回调延迟到下次DOM更新循环之后执行
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>
<ul ref="box">
<li v-for="(item, index) in arr" :key="index"></li>
</ul>
</template>
<script>
export default {
data() {
return {
arr: []
}
},
mounted() {
this.getData();
},
methods: {
getData() {
this.arr = [1, 2, 3];
this.$refs.box.getElementsByTagName('li')[0].innerHTML = 'hello';
}
}
}
</script> - 在DOM元素li还未渲染就调用会报错
- 可以将方法放到nextTick回调中
1
2
3this.$nextTick(() => {
this.$refs.box.getElementsByTagName('li')[0].innerHTML = 'hello';
}) - 也可以使用async/await
1
2
3
4
5
6
7
8
9methods: {
async getData() {
this.arr = [1, 2, 3];
await this.$nextTick();
this.$refs.box.getElementsByTagName('li')[0].innerHTML = 'hello';
}
}对低开销的静态组件使用v-once
- v-once指令用于只渲染元素和组件一次
- 一般可以用于存在大量静态数据组件的更新性能优化
1
<my-component v-once :data="msg"></my-component>
- msg 的值如何变化,组件内渲染的永远是其第一次获取到的初始值。
- 使用$isServer判断当前实例是否运行与服务器
- 使用$isServer则无需进行配置,在组件中直接使用API即可
1
2
3if (this.$isServer) {
document.title = 'test';
}