性能优化
1. vue路由的按需加载
将路由页面/触发性功能单独打包为一个文件,使用时才加载,好处是减轻首屏渲染的负担。因为项目功能越多其打包体积越大,导致首屏渲染速度越慢。 即在router中使用如下:
原:
import Vue from 'vue'
import VueRouter from 'vue-router'
import loading from '../views/loading.vue'
import test from '../views/test.vue'
Vue.use(VueRouter)
const routes = [{
path: '*',
redirect: '/loading'
},
{
path: '/loading',
name: 'loading',
component: loading
},
{
path: '/test',
name: 'test',
component: test,
}
];
const router = new VueRouter({
routes
})
改:
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const routes = [{
path: '*',
redirect: '/loading'
},
{
path: '/loading',
name: 'loading',
component: () => import('@/views/loading'),
},
{
path: '/test',
name: 'test',
component: () => import('@/views/test'),
}
];
const router = new VueRouter({
routes
})
export default router
区别明显可见于打包后,打出的js、css包的数量
2.vue部分代码层面优化
(1)合理使用v-if和v-show
(2)使用v-for必须添加key, 最好为唯一id, 避免使用index,v-for不要和v-if同时使用
(3)定时器的销毁。可以在beforeDestroy()生命周期内执行销毁事件
3.防抖、节流
大部分主流ui框架对input等的change事件都已做过防抖了,主要优化的是自己写的业务逻辑相关功能
防抖函数:
function debounce(fn,delay = 500){
let timer = null
return function(){
if(timer) {
clearTimeout(timer)
}
timer = setTimeout(()=>{
fn.apply(this,arguments)
timer = null
},delay)
}
}
核心逻辑是:连续触发时,通过setTimeout自动清除上一次的,再重新赋值一个新的,缺点是需要等待一个延时器的事件
节流函数:
function throttle(fn,delay = 500) {
let timer = null
return function() {
if(timer) {
return
}
timer = setTimeout(()=>{
fn.apply(this,arguments)
timer = null
},delay)
}
}