使用 Vue 做了几个项目了,总结下。。。
跨域解决
Chrome 添加参数 --disable-web-security --user-data-dir
webpack 的dev-server使用了非常强大的 http-proxy-middleware 包。
模板中表达式过多时(如v-if="isShow && hasRight && (foo || bar)"),适当的封装成computed和methods。
对于响应式的结果使用computed。
单次的使用methods。
不同时使用v-for和v-if。
v-for具有比v-if更高的优先级,应当先对循环的内容作用v-if条件的过滤,减少不必要的循环。不将有改变index交互的v-for列表使用index作为key。
提取公用方法。有返回值使用 filter, 没有返回值使用 mixin。
对于简单而直接的渲染重复内容可加上functional: true 就是无状态data。
无状态data更有效,更直接。对于不会修改的数据,可以使用Object.freeze()提升性能(不会做 getter、setter 绑定)。
使用bootcdn减小 vendor 的体积。index.html中引入资源,设置webpack的externals,忽略不需要打包的库。
<script src="//cdn.bootcss.com/vue/2.5.16/vue.min.js"></script>
<script src="//cdn.bootcss.com/vue-router/3.0.1/vue-router.min.js"></script>
externals: {
'vue': 'Vue',
'vue-router': 'VueRouter'
}
坑 使用 vue 的 min 版本,导致Devtools失效。使用webpack的HtmlWebpackPlugin解决。
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.html',
inject: true,
min: '' // 开发
// min: '.min' // 生产
})
<script src="//cdn.bootcss.com/vue/2.5.16/vue<%= htmlWebpackPlugin.options.min %>.js"></script>
inline 一些小文件,减少 http 请求。
使用inline-manifest-webpack-plugin将manifest文件进行inline。
使用html-webpack-inline-plugin将小文件进行inline。
使用路由懒加载拆分包。
lodash优化
坑 优化后的一些方法的的第二参数不能用字符串,要用回调。例子:
_.sumBy(objects, function(o) {
return o.n
}) // ok
_.sumBy(objects, 'n') // error
_.uniqBy([{ x: 1 }, { x: 2 }, { x: 1 }], function(o) {
return o.x
}) // ok
_.uniqBy([{ x: 1 }, { x: 2 }, { x: 1 }], 'x') // error
babal-pollyfill优化
@babel/preset-env,现在(2018-06-06)7.0.0 还是 beta 版本。moment优化
移除 console 和 debugger
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false,
drop_console: true,
drop_debugger: true
},
sourceMap: true
})
www.example.com/subdir。需要将 build 的assetsPublicPath改为/subdir/。如果路由使用的是history模式,还需要增加{ base: 'subdir' }。