vue性能优化与代码风格

性能

  • v-for设置key
    可复用元素,更新dom时,可根据key来识别唯一元素是否可复用,把dom变动成本降到最低
  • v-if和v-for避免用在同一个元素上,减少遍历运算成本和渲染成本
    • 过滤列表,将列表作为计算属性返回
    • 显示隐藏状态,将v-if移至父容器
  • 路由懒加载 异步组件
1
2
3
4
5
6
7
8
9
10
11
// Foo.vue
const Foo = () => Promise.resolve({
// ... 组件定义对象
})
// 引用组件,Babel需要添加 syntax-dynamic-import解析语法
const Foo = () => import('./Foo.vue')
const router = new VueRouter({
routes: [
{ path: '/foo', component: Foo }
]
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
module.exports = {
//...
// 代码分离的默认配置参数
optimization: {
splitChunks: {
chunks: 'async',
minSize: 30000, // vendor-chunk 大于30k
maxSize: 0,
minChunks: 1,
maxAsyncRequests: 5, // 按需加载的代码块,并行请求数量小于等于5
maxInitialRequests: 3, // 初始加载的代码块,并行请求数量小于等于5个
automaticNameDelimiter: '~',
name: true,
cacheGroups: {
vendors: { // 来自node_modules模块
test: /[\\/]node_modules[\\/]/,
priority: -10
},
default: {
minChunks: 2,
priority: -20,
reuseExistingChunk: true
}
}
}
}
};

代码风格

组件样式作用域

  • scoped
  • module,生成的css对象注入到组件的$style计算属性
  • BEM约定
    • .block 块
    • .block__element 元素
    • .block–modifier 修饰符
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
 <template><button class="button">X</button></template>
<!-- 使用 `scoped` 特性 -->
<style scoped>
.button {
border: none;
border-radius: 2px;
}
</style>

<template>
<button :class="[$style.button]">X</button></template>
<!-- 使用 CSS Modules -->
<style module>.button {
border: none;
border-radius: 2px;
}
</style>

<template><button class="c-Button c-Button--close">X</button></template>

<!-- 使用 BEM 约定 -->
<style>.c-Button {
border: none;
border-radius: 2px;
}
.c-Button--close {
background-color: red;
}
</style>

关于命名风格

  • 推荐用 $_ 作为私有属性
  • 单文件组件
    • 大驼峰
    • 横线连接 -
  • 通用基础组件名
    • Base html元素
    • App 其他基础组件
    • V 第三方ui组件库
  • 单例组件,每个页面只会使用一次
    • TheHeading.vue
  • 模块中紧密耦合的组件
    • 模块.vue
    • 模块Item.vue
  • 组件名使用
    • 单文件组件、字符串模板、Jsx中 使用自闭合,大驼峰
    • Dom模板中 使用闭合标签,横线连接 -