Implementation of code optimization for Vue2.x project performance optimization

Implementation of code optimization for Vue2.x project performance optimization

As we all know, the Vue project uses two-way data binding and virtual DOM as the basis. It is very efficient to use data-driven instead of DOM frequent rendering. It is already very optimized for developers. So why is there such a thing as Vue performance optimization?

Because Vue 2.x currently uses third-party packaging and construction tools such as webpack, and supports other third-party plug-ins, when we use these tools in our projects, different operations may have different effects on running or packaging efficiency. The following will explain in detail the optimization direction.

1 Use of v-if and v-show

  • When v-if is false, the DOM will not be rendered to the view, and it will be rendered to the view when it is true;
  • v-show The element is always rendered into view regardless of the initial conditions, it is simply toggled based on the CSS display property.

Best Practices: Use v-show for frequently toggled elements, and v-if for rarely changed elements

2. Differentiate between computed and watch

  • computed: It is a calculated property that depends on other property values. The computed value is cached. Only when the property value it depends on changes, the computed value will be recalculated the next time the computed value is obtained.
  • Watch: It is more of an "observation" function, similar to the monitoring callback of certain data. Whenever the monitored data changes, the callback will be executed for subsequent operations;

Best Practices: When we need to perform numerical calculations that depend on other data, we should use computed because we can take advantage of computed's caching properties to avoid recalculating each time we get a value. When we need to perform asynchronous or expensive operations when data changes, we should use watch. The watch option allows us to perform asynchronous operations (access an API), limit the frequency with which we perform the operation, and set intermediate states before we get the final result. These are things that computed properties cannot do.

3 v-for traversal must add a key to the item and avoid using v-if at the same time

If you don't add a key, an error will generally occur. Adding a key can make it easier for Vue's internal mechanism to accurately find the list data. When updating, the new status value is compared with the old status value to locate the diff more quickly

v-for has a higher priority than v-if. If you need to traverse the entire array every time, it will affect the speed, especially when only a small part needs to be rendered. If necessary, it should be replaced with a computed property.

<ul>
 <li v-for="user in adminUsers" :key="user.id">
  {{ user.name }}
 </li>
</ul>

<script>
export default {
 data () {
 return { users: [] }
 },
 computed: {
 adminUsers: function(){
 return this.users.filter(()=>user.isAdmin)
 }
 }
}
</script>

4. Performance optimization of pure display of long lists

For data that is only used for display, there is no need to use Vue to hijack the data, you only need to freeze the object:

export default {
 data () {
 return {
 users: []
 }
 },
 created () {
 axios.get('/api/users').then((res)=>{
 this.users = Object.freeze(res.data.users)
 })
 }
}
 

5. Event Destruction

When a Vue component is destroyed, it automatically cleans up its connections with other instances and unbinds all its instructions and event listeners, but only for events of the component itself. If addEventListene and other methods are used in js, the event will not be automatically destroyed. We need to manually remove the listeners of these events when the component is destroyed to avoid memory leaks, such as:

created() {
 addEventListener('click', this.click, false)
},
beforeDestroy() {
 removeEventListener('click', this.click, false)
}
 

6. Lazy loading of image resources

Use vue-lazyload plugin:

Install

npm install vue-lazyload --save-dev

man.js reference

import VueLazyload from 'vue-lazyload'
Vue.use(VueLazyload)
// or customize Vue.use(VueLazyload, {
 preLoad: 1.3,
 error: 'dist/error.png',
 loading: 'dist/loading.gif',
 attempt: 1
})

Modify the img tag

<img v-lazy="/static/img/1.png">

7 Routing lazy loading

Vue is a single-page application, which may have many routes introduced. Therefore, the file packaged with webpcak is very large. When entering the homepage, too many resources are loaded and the page will display a white screen, which is not conducive to user experience. It would be more efficient if we could split the components corresponding to different routes into different code blocks, and then load the corresponding components when the route is accessed. This will greatly increase the speed of the first screen display, but the speed of other pages may decrease.

const Foo = () => import('./Foo.vue')
const router = new VueRouter({
 routes: [
 { path: '/foo', component: Foo }
 ]
})

8. Introduce third-party plug-ins on demand

When we use third-party libraries, it is best to import them on demand rather than globally, because third-party libraries have many plug-ins and importing all of them will be slow to package, such as Element UI, Ant Design of Vue and other UI libraries:

Import on demand

import Vue from 'vue';
import { DatePicker } from 'ant-design-vue';
Vue.use(DatePicker);
 

Global import

import Antd from 'ant-design-vue';
Vue.use(Antd);

9 Optimizing infinite list performance

If you are rendering a list with infinite scrolling, you need to use windowing technology to optimize performance. You only need to render a small area of ​​content, reducing the time to re-render components and create DOM nodes. You can refer to the following open source projects vue-virtual-scroll-list and vue-virtual-scroller to optimize this infinite list scenario.
Please go to Github to read the instructions.

10. Server-side rendering SSR or pre-rendering

Generally, single-page applications complete page rendering on the browser side, and the data is obtained from the background by sending a request; while server-side rendering SSR means that the structure of the page elements (HTML) is already built on the server side, and the entire page is directly returned to the client.
So what are the advantages and disadvantages of SSR:

  • Better SEO: Web crawlers can directly crawl page information, which is conducive to being included in search engines, while the content of ajax asynchronous requests will not be included, so the complete page information rendered by SSR is more conducive to SEO;
  • The supported hook functions are only beforCreate and created, and the server needs to be in the Node Server environment;
  • Requires higher server configuration: Because it includes data processing and page rendering, the server cost becomes larger

If you have high requirements for the first screen loading speed or SEO, you can use SSR rendering.

PS: Optimization is just a suggestion. You need to consider whether it is suitable for your project, including the difficulty of optimization, the scope of impact, applicable scenarios, whether it affects other modules, whether the optimization effect is obvious, etc. What suits you is the best!

This concludes this article on the implementation of code optimization for Vue2.x project performance optimization. For more relevant Vue2.x code optimization content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • A practical guide to Vue project first screen performance optimization components
  • Vue.js performance optimization N tips (worth collecting)
  • The vue project enables Gzip compression and performance optimization operations
  • Methods for optimizing Vue performance
  • Speed ​​up the rendering of Vue components and optimize their performance
  • Summary of Vue first screen performance optimization component knowledge points

<<:  Nexus uses API to operate

>>:  Detailed explanation of MySQL 5.7.9 shutdown syntax example

Recommend

Implementation of Nginx hot deployment

Table of contents Semaphore Nginx hot deployment ...

Vue uses better-scroll to achieve horizontal scrolling method example

1. Implementation principle of scrolling The scro...

Vue implements fuzzy query-Mysql database data

Table of contents 1. Demand 2. Implementation 3. ...

Win2008 R2 mysql 5.5 zip format mysql installation and configuration

Win2008 R2 zip format mysql installation and conf...

MySQL multi-master and one-slave data backup method tutorial

Overview Operations on any one database are autom...

Basic knowledge: What does http mean before a website address?

What is HTTP? When we want to browse a website, w...

MySQL database SELECT query expression analysis

A large part of data management is searching, and...

js to realize a simple advertising window

This article shares the specific code of js to im...

Detailed tutorial for installing mysql5.7.21 under Windows

This article shares the installation tutorial of ...

Centos7 installation of Nginx integrated Lua sample code

Preface The computer I use is a Mac, and the oper...

Detailed tutorial on using VMware WorkStation with Docker for Windows

Table of contents 1. Introduction 2. Install Dock...

How to solve the abnormal error ERROR: 2002 in mysql

Recently, an error occurred while starting MySQL....

JS uses map to integrate double arrays

Table of contents Preface Simulating data Merged ...

Detailed explanation of custom swiper component in JavaScript

Table of contents Effect display Component Settin...

What do CN2, GIA, CIA, BGP and IPLC mean?

What is CN2 line? CN2 stands for China Telecom Ne...