Home  >  Article  >  Web Front-end  >  How to optimize performance in Vue development? 12 optimization tips to share

How to optimize performance in Vue development? 12 optimization tips to share

青灯夜游
青灯夜游forward
2022-02-24 11:35:073511browse

How to optimize performance in Vue development? This article will share with you 12 performance optimization tips in Vue development. I hope it will be helpful to everyone!

How to optimize performance in Vue development? 12 optimization tips to share

Performance optimization is a problem that every developer will encounter, especially now that more and more emphasis is placed on experience and in an increasingly competitive environment, for us For developers, it is not enough to just complete iterations and make the functions good. The most important thing is to make the product good so that more people are willing to use it and make it more enjoyable for users. Isn’t this also the value of our developers? Is it a manifestation of ability?

Paying attention to performance issues and optimizing product experience are much more valuable than fixing a few insignificant bugs

This article records some of my tips in daily development of Vue projects, nonsense Without further ado, let’s get started! [Related recommendations: vuejs video tutorial]

1. Long list performance optimization

1. Do not make responsive

such as member list and product list In a scenario where it is just a pure data display without any dynamic changes, there is no need to perform responsive processing on the data, which can greatly improve the rendering speed.

For example, use Object.freeze( ) Freeze an object. The description of MDN is that the object frozen by this method cannot be modified; that is, new attributes cannot be added to this object, existing attributes cannot be deleted, and the enumerability and reproducibility of existing attributes of the object cannot be modified. Configurability, writability, and the fact that the values ​​of existing attributes cannot be modified, and the prototype of the object cannot be modified either

export default {
 data: () => ({
   userList: []
}),
 async created() {
   const users = await axios.get("/api/users");
   this.userList = Object.freeze(users);
}
};

Vue2’s responsive source code address: src/core/observer/index. js - Line 144 is like this

export function defineReactive (...){
   const property = Object.getOwnPropertyDescriptor(obj, key)
   if (property && property.configurable === false) {
       return
  }
   ...
}

You can see that configurable is judged as false from the beginning and is returned directly without responsive processing

configurable is false means that this property cannot be modified, and the configurable of the frozen object is false

How to optimize performance in Vue development? 12 optimization tips to share

Vue3 adds responsive flag to mark the target object type

2. Virtual scrolling

If it is a long list of big data, creating too many DOMs at one time will be very stuck if it is rendered all at once. At this time, you can use virtual scrolling to only render the content of a small part (including the visible area) of the area, and then scroll , constantly replace the content of the visible area, simulating the effect of scrolling

<recycle-scroller
 class="items"
 :items="items"
 :item-size="24"
>
 <template v-slot="{ item }">
   <FetchItemView
     :item="item"
     @vote="voteItem(item)"
   />
 </template>
</recycle-scroller>

Refer to vue-virtual-scroller, vue-virtual-scroll-list

The principle is to monitor scrolling events and dynamic updates are required Display the DOM and calculate the displacement in the view, which also means that the scrolling process requires real-time calculation, which has a certain cost, so if the amount of data is not very large, just use ordinary scrolling

2. v-for traversal avoids using v-if

at the same time. Why should you avoid using v-for and v-if

at the same time in Vue2 v-for has a higher priority, so during the compilation process, all list elements will be traversed to generate a virtual DOM, and then v-if will be used to judge the qualified ones before rendering, which will cause a waste of performance, because we The hope is that no virtual DOM that does not meet the conditions will be generated.

In Vue3, v-if has a higher priority, which means that when the judgment condition is in the list traversed by v-for For attributes, v-if cannot be obtained

So in some scenarios that need to be used at the same time, you can filter the list by calculating the attributes, as follows

<template>
   <ul>
     <li v-for="item in activeList" :key="item.id">
      {{ item.title }}
     </li>
   </ul>
</template>
<script>
// Vue2.x
export default {
   computed: {
     activeList() {
       return this.list.filter( item => {
         return item.isActive
      })
    }
  }
}

// Vue3
import { computed } from "vue";
const activeList = computed(() => {
 return list.filter( item => {
   return item.isActive
})
})
</script>

3. List usage Unique key

For example, if we have a list and we need to insert an element in the middle, what will happen if we do not use a key or use index as the key? Let’s take a look at the picture first

How to optimize performance in Vue development? 12 optimization tips to share

li1 and li2 as shown in the picture will not be re-rendered. This is not controversial. And li3, li4, li5 will all be re-rendered

because key or index of the list is not used as key When , the corresponding position relationship of each element is index. The result in the above figure directly causes the corresponding position relationship from the element we inserted to all subsequent elements to change, so they will all be executed during the patch process. Update operation and re-render.

This is not what we want. What we want is to render the added element without making any changes to the other four elements, so we don’t need to re-render

but use the only one # In the case of ##key, the positional relationship corresponding to each element is key. Let’s take a look at the case of using a unique key value

How to optimize performance in Vue development? 12 optimization tips to share

这样如图中的 li3 和 li4 就不会重新渲染,因为元素内容没发生改变,对应的位置关系也没有发生改变。

这也是为什么 v-for 必须要写 key,而且不建议开发中使用数组的 index 作为 key 的原因

4. 使用 v-show 复用 DOM

v-show:是渲染组件,然后改变组件的 display 为 block 或 none  v-if:是渲染或不渲染组件

所以对于可以频繁改变条件的场景,就使用 v-show 节省性能,特别是 DOM 结构越复杂收益越大

不过它也有劣势,就是 v-show 在一开始的时候,所有分支内部的组件都会渲染,对应的生命周期钩子函数都会执行,而 v-if 只会加载判断条件命中的组件,所以需要根据不同场景使用合适的指令

比如下面的用 v-show 复用DOM,比 v-if/v-else 效果好

<template>
 <div>
   <div v-show="status" class="on">
     <my-components />
   </div>
   <section v-show="!status" class="off">
     <my-components >
   </section>
 </div>
</template>

原理就是使用 v-if 当条件变化的时候,触发 diff 更新,发现新旧 vnode 不一致,就会移除整个旧的 vnode,再重新创建新的 vnode,然后创建新的 my-components 组件,又会经历组件自身初始化,renderpatch 等过程,而 v-show 在条件变化的时候,新旧 vnode 是一致的,就不会执行移除创建等一系列流程

5. 无状态的组件用函数式组件

对于一些纯展示,没有响应式数据,没有状态管理,也不用生命周期钩子函数的组件,我们就可以设置成函数式组件,提高渲染性能,因为会把它当成一个函数来处理,所以开销很低

原理是在 patch 过程中对于函数式组件的 render 生成的虚拟 DOM,不会有递归子组件初始化的过程,所以渲染开销会低很多

它可以接受 props,但是由于不会创建实例,所以内部不能使用 this.xx 获取组件属性,写法如下

<template functional>
 <div>
   <div class="content">{{ value }}</div>
 </div>
</template>
<script>
export default {
 props: [&#39;value&#39;]
}
</script>

// 或者
Vue.component(&#39;my-component&#39;, {
 functional: true, // 表示该组件为函数式组件
 props: { ... }, // 可选
 // 第二个参数为上下文,没有 this
 render: function (createElement, context) {
   // ...
}
})

6. 子组件分割

先看个例子

<template>
 <div :style="{ opacity: number / 100 }">
   <div>{{ someThing() }}</div>
 </div>
</template>
<script>
export default {
 props:[&#39;number&#39;],
 methods: {
   someThing () { /* 耗时任务 */ }
}
}
</script>

上面这样的代码中,每次父组件传过来的 number 发生变化时,每次都会重新渲染,并且重新执行 someThing 这个耗时任务

所以优化的话一个是用计算属性,因为计算属性自身有缓存计算结果的特性

第二个是拆分成子组件,因为 Vue 的更新是组件粒度的,虽然第次数据变化都会导致父组件的重新渲染,但是子组件却不会重新渲染,因为它的内部没有任何变化,耗时任务自然也就不会重新执行,因此性能更好,优化代码如下

<template>
<div>  
 <my-child />
</div>
</template>
<script>
export default {
components: {  
 MyChild: {  
  methods: {    
   someThing () { /* 耗时任务 */ }    
  },   
   render (h) {  
    return h(&#39;div&#39;, this.someThing())  
  } 
 }
}
}
</script>

7. 变量本地化

简单说就是把会多次引用的变量保存起来,因为每次访问 this.xx 的时候,由于是响应式对象,所以每次都会触发 getter,然后执行依赖收集的相关代码,如果使用变量次数越多,性能自然就越差

从需求上说在一个函数里一个变量执行一次依赖收集就够了,可是很多人习惯性的在项目中大量写 this.xx,而忽略了 this.xx 背后做的事,就会导致性能问题了

比如下面例子

<template> 
 <div :style="{ opacity: number / 100 }"> {{ result
}}</div>
</template>
<script>
import { someThing } from &#39;@/utils&#39;
export default {
 props: [&#39;number&#39;], 
 computed: {  
  base () { return 100 },  
  result () {   
   let base = this.base, number = this.number // 
保存起来    
  for (let i = 0; i < 1000; i++) {   
   number += someThing(base) // 避免频繁引用
this.xx   
  }   
   return number 
  }
}
}
</script>

8. 第三方插件按需引入

比如 Element-UI 这样的第三方组件库可以按需引入避免体积太大,特别是项目不大的情况下,更没有必要完整引入组件库

// main.js
import Element3 from "plugins/element3";
Vue.use(Element3)

// element3.js
// 完整引入
import element3 from "element3";
import "element3/lib/theme-chalk/index.css";

// 按需引入
// import "element3/lib/theme-chalk/button.css";
// ...
// import { 
// ElButton, 
// ElRow, 
// ElCol, 
// ElMain, 
// .....
// } from "element3";

export default function (app) { 
// 完整引入 
app.use(element3)  

// 按需引入 
// app.use(ElButton);
}

9. 路由懒加载

我们知道 Vue 是单页应用,所以如果没有用懒加载,就会导致进入首页时需要加载的内容过多,时间过长,就会出现长时间的白屏,很不利于用户体验,SEO 也不友好

所以可以去用懒加载将页面进行划分,需要的时候才加载对应的页面,以分担首页的加载压力,减少首页加载时间

没有用路由懒加载:

import Home from &#39;@/components/Home&#39;
const router = new VueRouter({  
 routes: [  
  { path: &#39;/home&#39;, component: Home }
]
})

用了路由懒加载:

const router = new VueRouter({
routes: [ 
 { path: &#39;/home&#39;, component: () => 
import(&#39;@/components/Home&#39;) }, 
 { path: &#39;/login&#39;, component: 
require(&#39;@/components/Home&#39;).default }
]
})

在进入这个路由的时候才会走对应的 component,然后运行 import 编译加载组件,可以理解为 Promise 的 resolve 机制

  • import:Es6语法规范、编译时调用、是解构过程、不支持变量函数等
  • require:AMD规范、运行时调用、是赋值过程,支持变量计算函数等

更多有关前端模块化的内容可以看我另一篇文章 前端模块化规范详细总结

10. keep-alive缓存页面

比如在表单输入页面进入下一步后,再返回上一步到表单页时要保留表单输入的内容、比如在列表页>详情页>列表页,这样来回跳转的场景等

我们都可以通过内置组件 <keep-alive></keep-alive> 来把组件缓存起来,在组件切换的时候不进行卸载,这样当再次返回的时候,就能从缓存中快速渲染,而不是重新渲染,以节省性能

只需要包裹想要缓存的组件即可

<template>
 <div id="app"> 
  <keep-alive>  
   <router-view/> 
  </keep-alive>
</div>
</template>
  • 也可以用 include/exclude 来 缓存/不缓存 指定组件
  • 可通过两个生命周期 activated/deactivated 来获取当前组件状态

11. 事件的销毁

Vue 组件销毁时,会自动解绑它的全部指令及事件监听器,但是仅限于组件本身的事件

而对于定时器addEventListener 注册的监听器等,就需要在组件销毁的生命周期钩子中手动销毁或解绑,以避免内存泄露

<script>
export default {  
 created() {   
  this.timer = setInterval(this.refresh, 2000)  
  addEventListener(&#39;touchmove&#39;, 
this.touchmove, false) 
 }, 
  beforeDestroy() {  
   clearInterval(this.timer)   
   this.timer = null   
   removeEventListener(&#39;touchmove&#39;, 
this.touchmove, false) 
 }
}
</script>

12. 图片懒加载

图片懒加载就是对于有很多图片的页面,为了提高页面加载速度,只加载可视区域内的图片,可视区域外的等到滚动到可视区域后再去加载

这个功能一些 UI 框架都有自带的,如果没有呢?

推荐一个第三方插件 vue-lazyload

npm i vue-lazyload -S

// main.js
import VueLazyload from &#39;vue-lazyload&#39;
Vue.use(VueLazyload)

// 接着就可以在页面中使用 v-lazy 懒加载图片了
<img  v-lazy="/static/images/How to optimize performance in Vue development? 12 optimization tips to share" alt="How to optimize performance in Vue development? 12 optimization tips to share" >

或者自己造轮子,手动封装一个自定义指令,这里封装好了一个兼容各浏览器的版本的,主要是判断浏览器支不支持 IntersectionObserver API,支持就用它实现懒加载,不支持就用监听 scroll 事件+节流的方式实现

const LazyLoad = { 
// install方法 
install(Vue, options) {  
 const defaultSrc = options.default 
 Vue.directive(&#39;lazy&#39;, {  
  bind(el, binding) {   
   LazyLoad.init(el, binding.value, defaultSrc) 
 },   
  inserted(el) {     
   if (IntersectionObserver) {    
    LazyLoad.observe(el)     
  } else {      
    LazyLoad.listenerScroll(el)    
  }  
 }, 
})
}, 
// 初始化 
init(el, val, def) { 
 el.setAttribute(&#39;data-src&#39;, val)  
 el.setAttribute(&#39;src&#39;, def)
}, 
// 利用IntersectionObserver监听el
observe(el) {  
 var io = new IntersectionObserver((entries) => {  
  const realSrc = el.dataset.src    
 if (entries[0].isIntersecting) {   
  if (realSrc) {      
   el.src = realSrc       
   el.removeAttribute(&#39;data-src&#39;)    
  }   
 } 
}) 
 io.observe(el)
}, 
// 监听scroll事件
listenerScroll(el) {  
 const handler =
LazyLoad.throttle(LazyLoad.load, 300) 
 LazyLoad.load(el)  
 window.addEventListener(&#39;scroll&#39;, () => {   
  handler(el) 
 })
}, 
// 加载真实图片 
load(el) {  
 const windowHeight =
document.documentElement.clientHeight
 const elTop = el.getBoundingClientRect().top  
 const elBtm = 
el.getBoundingClientRect().bottom 
 const realSrc = el.dataset.src  
 if (elTop - windowHeight < 0 && elBtm > 0) {  
  if (realSrc) {     
   el.src = realSrc    
   el.removeAttribute(&#39;data-src&#39;)  
  } 
 }
}, 
// 节流 
throttle(fn, delay) {  
 let timer  
 let prevTime  
 return function (...args) {   
  const currTime = Date.now() 
  const context = this    
  if (!prevTime) prevTime = currTime  
  clearTimeout(timer)   
  
  if (currTime - prevTime > delay) {     
   prevTime = currTime      
   fn.apply(context, args)    
   clearTimeout(timer)      
   return   
 }  

 timer = setTimeout(function () {   
  prevTime = Date.now()  
  timer = null   
  fn.apply(context, args)   
}, delay) 
}
},
}
export default LazyLoad

使用上是这样的,用 v-LazyLoad 代替 src

<img  v-LazyLoad="xxx.jpg" / alt="How to optimize performance in Vue development? 12 optimization tips to share" >

(学习视频分享:vuejs教程web前端

The above is the detailed content of How to optimize performance in Vue development? 12 optimization tips to share. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete