編碼優化
1. 不要將所有的數據都放到 data
中,data
中的數據都會增加 getter
和 setter
,又會收集watcher
,這樣還佔內存。不需要響應式的數據我們可以定義在實例上。
<template>
<div class="hello">
<ul>
<li v-for="(item, index) in list" :key="index">
{{ item }}
</li>
</ul>
</div>
</template>
<script>
export default {
data () {
return {
list: [1, 2, 3, 4, 5]
}
}
}
</script>
代碼可以優化成這樣子:
<template>
<div class="hello">
<ul>
<li v-for="(item, index) in list" :key="index">
{{ item }}
</li>
</ul>
</div>
</template>
<script>
export default {
created () {
this.list = [1, 2, 3, 4, 5]
}
}
</script>
2. 在 v-for
綁定事件的時候可以使用事件代理,將事件綁定到外層元素上。
<template>
<div class="hello">
<ul>
<li v-for="(item, index) in list" :key="index" @click="todo">
{{ item }}
</li>
</ul>
</div>
</template>
代碼可以優化成這樣子:
<template>
<div class="hello">
<ul @click="todo">
<li v-for="(item, index) in list" :key="index">
{{ item }}
</li>
</ul>
</div>
</template>
3. 使用 keep-alive
緩存組件,防止組件來回的創建和銷燬這樣浪費性能。
<transition>
<keep-alive>
<router-view></router-view>
</keep-alive>
</transition>
4. 拆分組件,增加代碼的複用性,減少不必要的渲染。
5. 使用 v-show
代替 v-if
指令。
6. key
最好保證唯一性,提高 DOM-diff 的複用性能。
7. 合理的使用路由懶加載,異步組件。
const router = new VueRouter({
routes: [
{ path: '/foo', component: () => import('./Foo.vue') }
]
})
8 數據持久化,本地存儲,localStorage,sessionStorage。
加載優化
1. 第三方模塊按需加載,比如 element-ui 的按需加載,根據需要僅引入部分組件。
import { Button } from 'element-ui';
2. 圖片的懶加載,可以使用 vue-lazyload 庫。
用戶體驗
1.骨架屏2.pwa 使用的 H5 的離線緩存
SEO優化
1.預渲染插件 prerender-spa-plugin2.服務端渲染
打包優化
1.使用 cdn 加載第三方模塊2.多線程打包 happypack3.splitChunks 抽離公共文件4.sourceMap 生成源碼映射5.壓縮和緩存6. 閱讀《vue性能優化》瞭解更多