SoFunction
Updated on 2025-03-10

Performance optimization solution in Vue

Recently, some encoding methods that have improved performance have been used during the development process of Vue, so it was specially sorted out and can be used as coding specifications for subsequent Vue development.

Performance optimization solutions are mainly divided into three categories. Let’s talk about the application of these three categories of optimization solutions in detail below.

  • Reduce responsive use
  • Reduce DOM rendering
  • Reduce packaging volume

Reduce responsive use

The most convenient way to use in Vue is responsive variables. When reading object properties, collecting side effect function dependencies, and taking out side effect function dependencies when writing set properties. However, collecting dependencies and triggering dependencies will affect performance after all, so in scenarios where you clearly know that you do not need to use responsive variables, you should reduce the use of responsive variables.

1. Use computed to cache the calculation results

The difference between computed and ordinary methods is that computed willCache calculation results, it will only be recalculated when the content of the calculation changes, and ordinary methods will recalculate each time. Therefore, for values ​​with calculation logic, it is recommended to use computed to encapsulate a layer as much as possible

For example, the following example is to simply encapsulate props with one layer through computed and use the template

const getTooltipStyle = computed((): CSSProperties => {
  return {
    color: ,
    fontSize: ,
  };
});

2. Localized responsive variables

According to the principle of Vue responsive variables, each time you access responsive data, you will collect dependencies. Therefore, when you need to use responsive variables frequently, you can first store the responsive variables with a local variable and convert them into a non-responsive variable.

Can be used in Vue3unrefThis api is used to obtain the responsive variable parameter itself (directly passed in Vue2thisJust assign value)

const tableData = ref([]) 

const unrefTableData = unref(tableData) // Do a lot of operations after localizing the variable(item => {
  // Specific operation})

3. Functional Components (Vue2)

Functional components refer to components that only accept some prop parameters, no responsive data, and no instances. The main application is to create simple display components, such as title header, pure display form, etc. Because there is no responsive data and instances, the initialization speed is much faster than that of ordinary stateful components, and it also supports returning multiple nodes

The way to declare functional components in Vue2 is as follows

<!-- template How to declare -->
<template functional>
</template>

<!-- jsx How to declare -->
("list", {
	functional: true,
})

However, in Vue3, the performance of stateful components has been greatly improved, and there is almost no difference between stateless components (functional components). Stateful components also support returning multiple nodes, so the official also removed it.functionalHow to define functional components,Note that Vue3 is a functional component definition that is incompatible with Vue2., so if you plan to upgrade Vue3 in the future, it is not recommended to use functional components

Reduce DOM rendering pressure

1. Use v-show when DOM frequently switches display

This is an optimization solution for long talks with old people. The principle isv-ifandv-showThe difference in implementation methods, forv-ifDOM nodes are not rendered if the conditions are not met, forv-showIt is to render all the conditions and passdisplay: block / noneSwitch, so when switching frequently DOM display situations, usev-showThe performance will be relatively better, such as when an editable cell needs to frequently switch the editing and saving state

butv-showIt is not without disadvantages, because the situations of each branch will be rendered in advance. If there are many nodes and no frequent switching of states is required, usev-ifWould be a better choice

2. Keep-alive caches component status

When switching components in Vue, the internal state of the component will also be lost. For example, when we fill out a form, we switch to another component to fill in other information. After switching back to the previous form component, the original information filled in will be refreshed. In this case, the keep-alive component caches the component status.

The most common method is<router-view>Nested a layer in the tag<transition>Tags add transition animation effect when component switching, and then nest a layer<keep-alive>Tag caches component status, and finally use<component>Render dynamic components or elements

<router-view>
  <template #default="{ Component, route }">
    <transition>
      	<keep-alive>
           <component :is="Component" :key="" />
    	</keep-alive>
    </transition>
  </template>
</router-view>

3. Lazy loading of routes

We all know that Vue is a single page application. If you load all the routes you need to use when the first screen is loaded, it would be a waste of performance. Therefore, using lazy loading methods to load the routes and reduce the pressure on the first screen is a more reasonable solution.

Using lazy loading in vue-router requires returning a through arrow functionimportThe path to the component will only run when it is run to this component.importCompile and load components

const form: AppRouteRecordRaw = {
  path: "/basicForm",
  name: "BasicForm",
  component: () =&gt; import("/@/views/form/"),
  meta: {
    title: "Basic Form",
  },
};

export default form;

4. Lazy image loading

The reason why images are lazy loading is similar to those of lazy loading routes, both to reduce unnecessary rendering. For example, we have a very long page with a lot of data or pictures to display, but the visual height of the display screen is fixed, so content outside the screen height can be loaded until the page needs it, thereby reducing the rendering pressure in the screen area.

The principle of lazy image loading is: when the image appears in the current window,data-srcReplace withsrcLoading pictures, the three commonly used methods of judging the visual area are

  • ().top < (Element relative to window position < form height)
  • IntersectionObserverWhen it listens to the visible part of the target element reaching the screen height, the specified callback function is executed
  • loading="lazy"Attributes (the compatibility is not very good at the moment, referenceLazy loading - Web Performance

Use lazy images in Vue Recommendedvue-lazyloadThis plugin is directly passedv-lazyThis command can achieve lazy image loading effect

<ul>
  <li v-for="img in list">
    <img v-lazy="" >
  </li>
</ul>

5. Clear the timer and EventListener when component is destroyed

Sometimes we start in the projectsetTimeoutTo trigger some events regularly, such as timed reminder form saving, if the timer is not cleared in time when leaving the component orEventListener, many pages can easily cause page lag and memory leaks when they accumulate.

A common solution is before leaving the componentonBeforeUnmountClear the timer andEventListener

onBeforeUnmount(() => {
  try {
    instance?.destroy?.();
  } catch (error) {
     = null;
  }
})

ClearingEventListenerNote:Remove the same function. The click event cannot be cleaned in the first case, because they are different function objects, and the second method to point to the same function object is required.

// This situation does not take effect because it points to different function objects("click", () =&gt; ("Hello"))
("click", () =&gt; ("Hello"))

// Only by pointing to the same function object can the EventListener event be cleanedfunction handler() {
  ("Hello")
}

("click", () =&gt; handler)
("click", () =&gt; handler)

6. Use a unique key in the list

This is mainly related to the efficiency of the diff algorithm, so I also use it as a solution to reduce the pressure of DOM rendering. In our usev-forWhen rendering contents in a loop, each component needs to be assigned an id. In this way, when the component content is updated, the diff algorithm can find the changing nodes more efficiently through the id, making dom rendering faster. At the same time, it is necessary to note that the allocated id is not the index of the array, because once the array elements are added or decreased, the index will also change, which will lose the effect of id.

<template v-for="schema in getSchema" :key="">
  <form-item
    :schema="schema"
    :form-props="getProps"
    :all-default-values="defaultValueRef"
  />
</template>

Reduce packaging volume

1. Turn on gzip compression

gzip is a file compression format that is more suitable for text file compression. It usually reduces the volume by more than twice, so it is very suitable for code file compression

The packaging tool we are using now is webpack. If you enable gzip packaging in webpack, you can use itcompression-webpack-pluginThis plugin is configured as follows

const CompressionPlugin = require("compression-webpack-plugin");
 = {
  configureWebpack : {
    plugins: [
      new CompressionPlugin({
        test: /\.(js|css|json|html)&amp;/,
        tereshold: 10 * 1024, // Compress after more than 10k      })
    ]
  }
}

In addition to adding configuration to the code, it also requires support from the server. Nginx is commonly used in the front-end. The main configuration parameters for enabling gzip compression in Nginx are as follows.

# Turn on and off gzip modegzip on;

#gizp compression starting point, file is larger than 10k before compressiongzip_min_length 10k;

# gzip compression level, 1-9, the larger the number, the better the compression, and the more CPU time it takes, generally 5, no matter how big it is, the effect will not be obviousgzip_comp_level 5;

# The type of file to be compressed.gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript ;

#nginx For static file processing module, after opening, it will look for files ending in .gz, and return directly, and will not occupy the CPU for compression. If it cannot be found, it will not be compressed.gzip_static on

# Whether to add Vary: Accept-Encoding in the http header, it is recommended to enable itgzip_vary on;

# Set the buffer size required for compression, in units of 4k. If the file is 7k, apply for a 2*4k buffer.gzip_buffers 2 4k;

# Set the HTTP protocol version that gzip compression targetsgzip_http_version 1.1;

2. Introduce third-party components on demand

The UI components we usually use are generally large and complete, and rarely use them all in our projects, so introducing third-party components on demand can effectively reduce the volume of application packages.

Take the Element Plus component we are using now as an example,unplugin-vue-componentsandunplugin-auto-importThese two plugins are implemented (Refer to the official tutorial

First introduce two plugins

pnpm i -D unplugin-vue-components unplugin-auto-import

Then configure two plug-ins in Webpack

// 
const AutoImport = require('unplugin-auto-import/webpack')
const Components = require('unplugin-vue-components/webpack')
const { ElementPlusResolver } = require('unplugin-vue-components/resolvers')

 = {
  // ...
  plugins: [
    AutoImport({
      resolvers: [ElementPlusResolver()],
    }),
    Components({
      resolvers: [ElementPlusResolver()],
    }),
  ],
}

This is the end of this article about the performance optimization solution in Vue. For more related Vue performance optimization content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!