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

MySQL decimal unsigned update negative numbers converted to 0

Today, when verifying the concurrency problem of ...

Teach you step by step to configure MySQL remote access

Preface When using the MySQL database, sometimes ...

Steps to set up Windows Server 2016 AD server (picture and text)

Introduction: AD is the abbreviation of Active Di...

Example code for implementing 3D Rubik's Cube with CSS

Let's make a simple 3D Rubik's Cube today...

Record a slow query event caused by a misjudgment of the online MySQL optimizer

Preface: I received crazy slow query and request ...

Page Refactoring Skills - Javascript, CSS

About JS, CSS CSS: Stylesheet at the top Avoid CS...

How to use lodop print control in Vue to achieve browser compatible printing

Preface This control will have a watermark at the...

What is the use of the enctype field when uploading files?

The enctype attribute of the FORM element specifie...

How does MySQL implement ACID transactions?

Preface Recently, during an interview, I was aske...

How to use limit_req_zone in Nginx to limit the access to the same IP

Nginx can use the limit_req_zone directive of the...

Detailed explanation of using scp command to copy files remotely in Linux

Preface scp is the abbreviation of secure copy. s...

Web data storage: Cookie, UserData, SessionStorage, WebSqlDatabase

Cookie It is a standard way to save the state of ...

How to use docker to deploy front-end applications

Docker is becoming more and more popular. It can ...