Home > Web Front-end > Vue.js > 12 tips! Take you to optimize performance in Vue development

12 tips! Take you to optimize performance in Vue development

WBOY
Release: 2022-02-22 17:53:02
forward
1871 people have browsed it

This article brings you relevant knowledge about vue, and mainly introduces 12 performance optimization tips in development. I hope it will be helpful to everyone.

12 tips! Take you to optimize performance in Vue development

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 the product experience are much more valuable than fixing a few innocuous bugs

This article records some of my tips in daily development of the Vue project. Without further ado, let’s get started. Bar!

1. Long list performance optimization

1. Not responsive

For example, member list, product list, etc., just pure data In scenarios where there will not be any dynamic changes, there is no need to perform responsive processing on the data, which can greatly improve the rendering speed. [Related recommendations: vue.js video tutorial]

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

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

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

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

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

configurable is represented by false This property cannot be modified, and the configurable of the frozen object is false

12 tips! Take you to optimize performance in Vue development

which is added in Vue3 Responsive flag, used to mark the target object type. For details on Vue3’s responsiveness, please see my other article

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>
  <template>
    <fetchitemview></fetchitemview>
  </template></recycle-scroller>
Copy after login

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 determine whether the conditions are met before rendering, which will cause a waste of performance, because we What we 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>
        {{ item.title }}
      </li>
    </ul></template><script>// Vue2.xexport default {
    computed: {
      activeList() {
        return this.list.filter( item => {
          return item.isActive        })
      }
    }}// Vue3import { computed } from "vue";const activeList = computed(() => {
  return list.filter( item => {
    return item.isActive  })})</script>
Copy after login

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

12 tips! Take you to optimize performance in Vue development

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

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 do not need to re-render

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

12 tips! Take you to optimize performance in Vue development

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

这也是为什么 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>
  <p>
    </p>
<p>
      <my-components></my-components>
    </p>
    <section>
      <my-components>
    </my-components></section>
  </template>
Copy after login

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

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

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

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

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

<template>
  <p>
    </p>
<p>{{ value }}</p>
  </template><script>export default {
  props: [&#39;value&#39;]}</script>// 或者Vue.component('my-component', {
  functional: true, // 表示该组件为函数式组件
  props: { ... }, // 可选
  // 第二个参数为上下文,没有 this
  render: function (createElement, context) {
    // ...
  }})
Copy after login

6. 子组件分割

先看个例子

<template>
  <p>
    </p>
<p>{{ someThing() }}</p>
  </template><script>export default {
  props:[&#39;number&#39;],
  methods: {
    someThing () { /* 耗时任务 */ }
  }}</script>
Copy after login

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

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

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

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

7. 变量本地化

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

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

比如下面例子

<template>
  <p> {{ result }}</p></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>
Copy after login

8. 第三方插件按需引入

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

// main.jsimport 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);}
Copy after login

9. 路由懒加载

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

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

没有用路由懒加载:

import Home from '@/components/Home'const router = new VueRouter({
  routes: [
    { path: '/home', component: Home }
  ]})
Copy after login

用了路由懒加载:

const router = new VueRouter({
  routes: [
    { path: '/home', component: () => import('@/components/Home') },
    { path: '/login', component: require('@/components/Home').default }
  ]})
Copy after login

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

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

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

10. keep-alive缓存页面

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

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

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

<template>
  <p>
    <keep-alive>
      <router-view></router-view>
    </keep-alive>
  </p></template>
Copy after login
  • 也可以用 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>
Copy after login

12. 图片懒加载

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

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

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

npm i vue-lazyload -S
// main.jsimport VueLazyload from 'vue-lazyload'Vue.use(VueLazyload)
// 接着就可以在页面中使用 v-lazy 懒加载图片了<img  alt="12 tips! Take you to optimize performance in Vue development" >
Copy after login

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

const LazyLoad = {
  // install方法
  install(Vue, options) {
    const defaultSrc = options.default
    Vue.directive('lazy', {
      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('src', val)
    el.setAttribute('src', 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('src')
        }
      }
    })
    io.observe(el)
  },
  // 监听scroll事件
  listenerScroll(el) {
    const handler = LazyLoad.throttle(LazyLoad.load, 300)
    LazyLoad.load(el)
    window.addEventListener('scroll', () => {
      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) {
      if (realSrc) {
        el.src = realSrc
        el.removeAttribute('src')
      }
    }
  },
  // 节流
  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
Copy after login

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

<img  alt="12 tips! Take you to optimize performance in Vue development" >
Copy after login

13. SSR

这一点我在项目中也没有实践过,就不班门弄斧了,关于 SSR 的优化可以看这篇文章: Vue-SSR 优化方案详细总结,这里记录一下,就不搬过来了

(学习视频分享:web前端

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

Related labels:
vue
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template