前言
接触vue框架差不多两个年头了,在磕磕绊绊中也了解到了一些常用的优化技巧,下面就简单介绍一下。
一、常见的优化方式?
1、大量数据使用分页、虚拟列表插件
2、图片懒加载
3、路由懒加载
4、为v-for循环添加唯一key值
5、使用keep-alive缓存组件的状态,防止多次渲染
二、不常见的优化方式
1.避免v-for与v-if在同一个标签内使用
原因:v-for的优先级比v-if高,放在同一个标签内使用,会先进行v-for进页面节点全部渲染出来,然后再用v-if判断显隐,会将false的节点删除,造成不必要的渲染。
解决办法如下:使用计算属性在节点渲染之前将不必要渲染的节点过滤掉。
// HTML模板
<h2 v-for="child in children">
{{child.title}}
</h2>
// JS代码
data(){
return{
children:[
{title:'foo',ifShow:true,id:0},
{title:'foo1',ifShow:true,id:1},
{title:'foo2',ifShow:false,id:2},
{title:'foo3',ifShow:false,id:3},
],
}
},
computed:{
detArr(){
return this.children.filter(item => item.ifShow === true)
}
}
2.函数式组件
vue中的函数式组件没有生命周期钩子,可以用来完成静态组件(没有对数据进行操作,只展示页面的组件)
<template functional>
<div>
<h1>我是函数式组件</h1>
<button v-for="(item,index) in props.list" :key="index">{{item.name}}</button>
</div>
</template>
<script>
export default {
name: "FunctionCom",
// 父组件传递过来的数据
props:{
list:{
required: true,
type:Array
}
}
}
</script>
<style scoped>
</style>
3.数据冻结
vue中的响应式原理就是给data中定义的数据添加get和set方法,实现数据拦截。我们可以对只用来展示的数据进行冻结。
冻结前:

冻结后:

相比于冻结前,每个属性都少了get和set方法,渲染速度更快。
4.变量本地化
当我们需要一个方法中使用data中的数据进行大量使用,但不改变他们的时候
methods:{
test(){
// 本地化之前
let result = 0
console.time('AAA'
for (let i = 0;i < 999999; i++){
result += this.m * this.n + this.m * this.m + this.n * this.n
}
console.timeEnd('AAA')
// 本地化之后
let res = 0
const {m, n} = this
console.time('BBB')
for (let i = 0;i < 999999; i++){
res += this.m * this.n + this.m * this.m + this.n * this.n
}
console.timeEnd('BBB')
}
}