Organize some common Vue performance optimization methods

The template

Use V-show and V-if for scenarios

  • V-if is rendered only if the expression returns true. If it returns false, the element does not exist in the document.

  • The v-show command will render whatever the return value of the expression is, based on the CSS property display control

While v-if is good for initialization, V-show is more good for update

To frequently switch the display status, use v-show; otherwise, use V-if

Avoid using v-for and V-if together

  • v-forv-ifThere is a priority problem, you canv-ifUse on the outer template

V-for traversal adds a key to each item and does not use index

Set a unique key value for each item, so that diFF comparison can accurately update the difference

Use keep – the alive

<template>
	<div>
    	<keep-alive>
        	<component :is="currentComponent" />
    	</keep-alive>
    </div>
</template>
Copy the code

The keep-alive function is to cache the component wrapped in it after the first rendering. The next time it is needed, it will be directly fetched from the cache to improve the loading speed of the component. However, note that the component will occupy memory when it is cached.

Computed and Watch distinguish usage scenarios

  • Computed attributes: New values are computed based on the values of dependencies, which are cached and recalculated when the values of dependencies change

  • Watch listener: Listens for data changes to perform subsequent operations

Computed can do it, watch can do it

Watch can do this, but computed may not, for example, do it asynchronously

Use computed It is recommended to use computed because of caching

The script to optimize

The data level should not be too deep

  • Prevent the data recursive response process from being too long

Use functional components

  • Only data is displayed, no listening management is required, no instance creation is required for initialization, state initialization, life cycle handling, etc
<template functional>
  <div class="user-profile">{{ props.name }}</div>
</template>
Copy the code

Use asynchronous components wisely

  • Use () => import()

  • defineAsyncComponent(() => import(“./AsyncComp.vue”))

Long list performance optimization

  • No need for Vue to hijack data to achieve view response data, pure data presentation
  • Freeze to freeze an Object. Once the Object is frozen, it cannot be modified
export default {
    data() {
        return {
            users: {}}}async created() {
        const users = await axios.get("/api/users");
        this.users = Object.freeze(users); }};Copy the code

Optimize infinite list performance

  • If your application has long or infinitely scrolling lists, use windowing techniques to optimize performance
  • Only a small portion of the content needs to be rendered, reducing the time needed to re-render components and create DOM nodes

Custom events and DOM destruction

  • For example, use within JSaddEventListenerEvents bound by such methods will not be automatically destroyed when the component is destroyed, so we need to manually remove them to avoid memory leaks
created() {
    addEventListener('click'.this.handleClick, false)},beforeDestroy() {
    removeEventListener('click'.this.handleClick, false)}Copy the code

Lazy loading of image resources

  • IntersectionObserver webAPI or the IntersectionObserver plug-in is used to monitor whether the IntersectionObserver enters the visible area, and then images or required data are loaded

Route lazy loading

  • Load the corresponding component only when the route is accessed, which improves the loading speed of the first screen and reduces the speed of other pages
const router = new VueRouter({
    routes: [{path: '/foo'.component:() = > import('./Foo.vue')}]})Copy the code

The introduction of third-party plug-ins on demand

  • Introduce third-party plug-ins, such as the Element component library, and introduce only the components needed to reduce the size of the project

Server rendering SSR

The task of rendering HTML is done on the server side and then returned directly to the client

advantages

  • The first screen loads faster and there is no need to wait for JS files to download before rendering
  • More SEO friendly, search engines don’t wait to crawlAjaxAsynchronously get data, whileSSRThe page containing the data is returned

disadvantages

  • Server development and load load increased