vue項(xiàng)目中,經(jīng)常會(huì)遇到一些性能優(yōu)化點(diǎn)轻姿,以下就是我在工作中犁珠,總結(jié)的優(yōu)化點(diǎn)
vue 性能優(yōu)化點(diǎn)
1,路由懶加載
{
path: '/nextTick',
name: 'nextTick',
component: resolve => require(['@/components/nextTick.vue'], resolve)
// component: () => import(/* webpackChunkName: "about" */ '@/components/nextTick.vue'),
},
2互亮,keep-alive 緩存頁(yè)面
<div>
<keep-alive>
<router-view v-if="$route.meta.keepAlive" />
</keep-alive>
<router-view v-if="!$route.meta.keepAlive" />
</div>
3犁享,多使用 v-show,少使用v-if
因?yàn)関-show只會(huì)重繪豹休,不需要操作DOM饼疙,而v-if就會(huì)觸發(fā)重排,操作DOM
4慕爬,v-for 遍歷盡量避免同時(shí)使用v-if
1窑眯,顯然v-for優(yōu)先于v-if被解析。
2医窿,如果同時(shí)出現(xiàn)磅甩,每次渲染都會(huì)先執(zhí)行循環(huán)再判斷條件,無(wú)論如何循環(huán)都不可避免姥卢,浪費(fèi)了性能卷要。
3,要避免出現(xiàn)這種情況独榴,則在外層嵌套template僧叉,在這一層進(jìn)行v-if判斷,然后在內(nèi)部進(jìn)行v-for循環(huán)棺榔。
4瓶堕,如果條件出現(xiàn)在循環(huán)內(nèi)部,可通過(guò)計(jì)算屬性提前過(guò)濾掉那些不需要顯示的項(xiàng)症歇。
5郎笆,長(zhǎng)列表優(yōu)化
- 如果純展示,可以凍結(jié)數(shù)據(jù)忘晤,無(wú)須做響應(yīng)式
export default {
data: () => ({
users: []
}),
async created() {
const users = await axios.get("/api/users"); this.users = Object.freeze(users);
}
};
- 虛擬滾動(dòng)宛蚓,只渲染少部分區(qū)域內(nèi)容 vue-virtual-scroller
6,事件銷毀设塔,比如:定時(shí)器
created() {
this.timer = setInterval(this.refresh, 2000)
},
beforeDestroy() {
clearInterval(this.timer)
}
7凄吏,圖片懶加載 <img v-lazy="xxx">
// 1,安裝
npm install vue-lazyload --save-dev
// 2,在入口文件main.js中引入并使用
import VueLazyload from 'vue-lazyload'
Vue.use(VueLazyload, {
loading: require('img/loading.png'), //加載中圖片痕钢,一定要有图柏,不然會(huì)一直重復(fù)加載占位圖
error: require('img/error.png') //加載失敗圖片
});
// 3,修改圖片顯示方式為懶加載
// img
<img v-lazy="'/static/img/' + item.productImage" :key="'/static/img/' + item.productImage">
//將 :src 屬性直接改為v-lazy, :key是為了防止刷新頁(yè)面或圖片更改時(shí)圖片不更新
// 背景圖
<div v-lazy:background-image="{src: item.imgpath}"></div>
`簡(jiǎn)單來(lái)說(shuō)盖喷,就是圖片屬性直接改為v-lazy爆办,兩者進(jìn)行切換,來(lái)實(shí)現(xiàn)懶加載`
8课梳,第三方庫(kù)按需引入
import Vue from 'vue';
import { Button, Select } from 'element-ui';
Vue.use(Button)
Vue.use(Select)
9距辆,無(wú)狀態(tài)的組件標(biāo)記為函數(shù)式組件:運(yùn)行時(shí),消耗資源較小
<template functional>
<div class="cell">
我的函數(shù)式組件展示
</div>
</template>
<script>
export default {}
</script>
10暮刃,子組件分割:需要經(jīng)常渲染的組件單獨(dú)拆分跨算,避免整個(gè)父組件渲染耗時(shí)長(zhǎng)
當(dāng)子組件需要來(lái)回反復(fù)進(jìn)行渲染時(shí),我們可以把他單獨(dú)抽出來(lái)椭懊,這樣就會(huì)避免該組件中其他的組件跟著重復(fù)渲染诸蚕,降低性能損耗
11,變量本地化:如果數(shù)據(jù)是固定值氧猬,盡量避免計(jì)算屬性重復(fù)調(diào)用背犯,減少性能損耗
<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。let result = this.start
for (let i = 0; i < 1000; i++) {
result += heavy(base)
}
return result
}
}
}
</script>