1. 路由懒加载
const router = new VueRouter({
routes: [
{ path: '/foo', component: () => import('./Foo.vue') } ]
})
2. keep-live 缓存组件
<template>
<div id="app">
<keep-alive>
<router-view/>
</keep-alive>
</div>
</template>
3. 列表添加key
确保唯一性,提高diff算法比较时间
4. 列表绑定事件使用事件代理(v-for)
把v-for监听放在外部判断
<div @click="handleClick">
<span
v-for="(item, index) of 100000"
:key="index" >
{{item}}
</span>
</div>
5. v-if 和 v-for不同时使用
因为for优先,可以提取在外层先v-if判断
6. 展示不变的大列表数据object.freeze冻结,不触发响应逻辑。
let list = Object.freeze(res.data);
7. 在需要复用大量数据显示的场景,使用v-show 代替v-if
8. 使用虚拟滚动
对于大数据展示,可以使用虚拟滚动,先渲染可视力=范围 vue-virtual-scroller,vue-virtual-scroll-list
9. 组件销毁时,手动解绑
只会自动解绑全部指令和事件绑定,仅仅限于组件本身,像setInterval需要手动解除
created() {
this.timer = setInterval(this.refresh, 2000) },
beforeDestroy() {
clearInterval(this.timer)
}
10.图片懒加载 vue-lazyload
<img v-lazy="/static/img/1.png">
11.第三方插件按需引入
element-ui的第三方组件库可以按需引入
import Vue from 'vue';
import { Button, Select } from 'element-ui';
Vue.use(Button) Vue.use(Select)
12.无状态的组件标记为函数式组件
<template functional>
<div class="cell">
<div v-if="props.value" class="on"></div> <section v-else class="off"></section>
</div>
</template>
<script>
export default {
props: ['value']
}
</script>
13.子组件分割
<div>
<ChildComp/>
</div>
</template>
<script>
export default {
components: {
ChildComp: {
methods: {
heavy () { /* 耗时任务 */ }
},
render (h) {
return h('div', this.heavy())
}
}
}
}
</script>
14.变量本地化
<template>
<div :style="{ opacity: start / 300 }">
{{ result }}
</div>
</template>
<script>
import { heavy } from '@/utils'
export default {
props: ['start'],
computed: {
base () { return 42 },
result () {
const base = this.base // 不要频繁引用this.base,而base 是计算后确定的结果
let result = this.start
for (let i = 0; i < 1000; i++) { //如果直接用this.base,会重复调用方法base () 有可能会触发拦截各种方法,导致影响性能。
result += heavy(base) //这里假设heavy是一个很耗性能的方法
}
return result
}
}
}
</script>
15. 使用SSR服务端渲染
- 使用vue-server-renderer + express,在服务端渲染后,返回字符串内容给前端。
- 使用nuxt.js 框架编写SSR 对于SEO,首屏优化都非常好,但维护性差,开发比较复杂。