search
HomeWeb Front-endVue.jsHow to optimize performance in Vue.js? 9 tips to share

How to optimize performance in Vue.js? 9 tips to share

Apr 12, 2022 pm 08:45 PM
vue.jsPerformance optimization

How to optimize performance in Vue.js? The following article will share with you nine tips for performance optimization in Vue.js. I hope it will be helpful to you!

How to optimize performance in Vue.js? 9 tips to share

(Learning video sharing: vuejs tutorial)

01 Functional components

How to optimize performance in Vue.js? 9 tips to share

How to optimize performance in Vue.js? 9 tips to share

**Principle: ****Functional component**Compared with ordinary components, it has no state (no responsiveness data), no instance (no this context). We can think of a functional component as a function in the component. The input parameter is the render context and the return value is the rendered HTML. Precisely because functional components simplify a lot of processing such as responsiveness and hook functions, rendering performance will be improved to a certain extent.

Applicable scenarios:

  1. Pure display components that do not require responsive data and processing logic

  2. Higher-order components used to mark or provide basic functions

  3. Elements in the loop (v-for)

02 Child component splitting

How to optimize performance in Vue.js? 9 tips to share

2-How to optimize performance in Vue.js? 9 tips to share

**Principle: **In the code before optimization, every time the number passed in props occurs It will be re-rendered when it changes, and the heavy function will be called again during the rendering process to perform performance-consuming operations. The optimized code logic is to encapsulate complex operations in sub-components. Since Vue updates are at component granularity, when the incoming number changes, the parent component will be re-rendered, and the sub-component does not depend on the number because it does not depend on the number. Will not re-render. The number of calculations performed is reduced, and the performance is naturally improved.

**Another: **You can actually use computed properties to optimize here (it will not be recalculated when the external dependencies have not changed, and the cost of additional rendering of subcomponents is saved)

03 Local variables

How to optimize performance in Vue.js? 9 tips to share

3-How to optimize performance in Vue.js? 9 tips to share

**Principle: **Comparing the before and after code, you can find that the difference is: before optimization The code directly references this.base every time it performs calculations, and the optimized code caches this.base using the local variable base, and calls the local variable for calculations in subsequent calculations. Why is there such an obvious performance difference? The reason is that every time this.base is accessed, since this.base is a calculated property, a piece of logic code will be executed to see if the existing dependencies have changed. If they have changed, they will be recalculated. If not, the last calculated value will be returned. The performance consumption of this type of calculation logic may not be obvious when it is called only a few times, but if it is executed too much (similar to the example where 300 components are updated per frame, and each component calls this.base multiple times within one update), then There will be a relatively large performance difference.

04 Reuse DOM with v-show

How to optimize performance in Vue.js? 9 tips to share

4-How to optimize performance in Vue.js? 9 tips to share

##Principle:

  • Implementation method: v-if dynamically adds or deletes DOM elements to the DOM tree, v-show controls visibility by setting the display style attribute of the DOM element.

  • Compilation process: v-if switching has a partial compilation and uninstallation process. During the switching process, internal event listeners and sub-components are properly destroyed and rebuilt. v-show is simply based on CSS. switch.

  • Compilation conditions: v-if is lazy, if the initial condition is false, do nothing, and only start partial compilation when the condition becomes true for the first time, v -show is compiled under all conditions, then cached, and the DOM elements are preserved.

  • Performance consumption: v-if has a higher switching cost, v-show has a higher initial rendering cost.

  • Сценарии использования: v-if подходит для ситуаций, когда условия вряд ли изменятся, v-show подходит для ситуаций, когда условия часто переключаются.

05 Keep-alive

How to optimize performance in Vue.js? 9 tips to share

5-How to optimize performance in Vue.js? 9 tips to share

5-How to optimize performance in Vue.js? 9 tips to share

##**Принцип: **В неоптимизированных сценариях каждый раз, когда мы нажимаем кнопку для переключения вида маршрутизации, компонент будет повторно визуализирован.Компонент рендеринга будет проходить через инициализацию компонента, рендеринг, исправление и другие этапы. Если компонент более сложный или вложенность более глубокая, весь рендеринг займет много времени. После использования KeepAlive vnode и DOM компонента, обернутого KeepAlive, будут кэшироваться после первого рендеринга, а затем при следующем рендеринге компонента соответствующие vnode и DOM будут получены непосредственно из кеша. нет необходимости проходить ряд процессов, таких как инициализация компонентов, рендеринг и патч и т. д., что сокращает время выполнения скрипта и обеспечивает лучшую производительность.

Но использование компонента KeepAlive не обходится без затрат, поскольку он будет занимать больше памяти для кеширования.Это типичное применение идей оптимизации пространства-времени.

06 Отложенные функции

How to optimize performance in Vue.js? 9 tips to share

где deferMixin имеет следующий вид:

6-How to optimize performance in Vue.js? 9 tips to share

6-How to optimize performance in Vue.js? 9 tips to share

6-How to optimize performance in Vue.js? 9 tips to share

##**Принцип: **Основная идея Defer состоит в том, чтобы разделить один рендеринг компонента на несколько раз. Он поддерживает внутреннюю переменную displayPriority. , а затем передает requestAnimationFrame. Он увеличивается при рендеринге каждого кадра до заданного значения. Затем внутри компонента, использующего миксин Defer, вы можете использовать v-if="defer(xxx)" для управления рендерингом определенных блоков, когда displayPriority увеличивается до xxx.

Если у вас есть компоненты, рендеринг которых требует времени, рекомендуется использовать Deferred для прогрессивного рендеринга. Это позволит избежать зависания рендеринга из-за слишком длительного выполнения JS.

07 Временное разделение

How to optimize performance in Vue.js? 9 tips to share

7-How to optimize performance in Vue.js? 9 tips to share

7-How to optimize performance in Vue.js? 9 tips to share

** Принцип : **Использование разделения времени позволяет избежать одновременной отправки слишком большого количества данных, что приведет к слишком длительному внутреннему времени выполнения JS, блокировке процесса пользовательского интерфейса и зависанию страницы.

**Еще: **При выполнении трудоемкой обработки задач мы обычно добавляем эффект загрузки, но путем сравнения до и после оптимизации можно обнаружить, что до оптимизации JS работал уже долгое время , блокируя процесс пользовательского интерфейса, поэтому он не Анимация загрузки не будет отображаться; после оптимизации, поскольку трудоемкая задача разделена на несколько временных интервалов для отправки, время выполнения одного JS сокращается, а анимация загрузки также имеет шанс быть оказанным.

08 Нереактивные данные

How to optimize performance in Vue.js? 9 tips to share

8-How to optimize performance in Vue.js? 9 tips to share

8-How to optimize performance in Vue.js? 9 tips to share

#* *Принцип:** При внутренней отправке данных вновь отправленные данные будут определены как адаптивные по умолчанию. Если дочернее свойство объекта является объектом, оно также будет рекурсивно сделано адаптивным. Поэтому, когда передается слишком много данных, весь процесс занимает очень много времени. После оптимизации флаг атрибута, настраиваемый в данных, вручную изменяется на false, так что массив атрибутов объекта, полученный внутри через Object.keys(obj), будет игнорировать данные, а атрибут данных не будет определен как активный, поскольку данные указывают на объект. , что также уменьшит логику рекурсивного ответа, что эквивалентно уменьшению потери производительности этой части. Чем больше объем данных, тем очевиднее будет эффект от такой оптимизации.

Разница между настройкой configurable и непосредственным использованием Object.freeze заключается в следующем:

**configurable: false** используется для предотвращения изменения и удаления флагов атрибутов, но разрешает изменение значения объекта;

**Object.freeze(obj)** Добавление/удаление/изменение атрибутов запрещено. Установите configurable: false, writable: false для всех существующих свойств.

// configurable: false

let user = {
  name: "John"
};

Object.defineProperty(user, "name", {
  configurable: false
});

user.name = "Pete"; // 正常工作
delete user.name; // Error

// Object.freeze(obj)

let user = {
  name: "John"
};

Object.freeze(user);

user.name = "Pete";
console.log(user.name); // "John"复制代码

09 Виртуальная прокрутка

How to optimize performance in Vue.js? 9 tips to share

##**Принцип:**Виртуальная прокрутка реализуется путем рендеринга только DOM в пределах диапазона просмотра. , производительность, естественно, будет намного выше при рендеринге меньшего количества контента. Компонент виртуальной прокрутки также написан

Guillaume Chau. Заинтересованные студенты могут изучить его реализацию исходного кода. Основной принцип заключается в отслеживании событий прокрутки, динамическом обновлении элементов DOM, которые необходимо отображаются и вычисляют их смещение в пределах вида. Компонент виртуальной прокрутки требует затрат, поскольку его необходимо рассчитывать в реальном времени во время процесса прокрутки, поэтому потребуется определенная стоимость выполнения сценария. Поэтому, если объем данных в списке не очень велик, нам достаточно использовать обычную прокрутку

Эта статья воспроизведена по адресу: https://juejin.cn/post/7084809333740929061

(Обучающее видеообмен:

разработка веб-интерфейса)

The above is the detailed content of How to optimize performance in Vue.js? 9 tips to share. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
Vue.js and the Frontend: Building Interactive User InterfacesVue.js and the Frontend: Building Interactive User InterfacesMay 06, 2025 am 12:02 AM

Vue.js is a progressive framework suitable for building highly interactive user interfaces. Its core functions include responsive systems, component development and routing management. 1) The responsive system realizes data monitoring through Object.defineProperty or Proxy, and automatically updates the interface. 2) Component development allows the interface to be split into reusable modules. 3) VueRouter supports single-page applications to improve user experience.

What are the disadvantages of VueJs?What are the disadvantages of VueJs?May 05, 2025 am 12:06 AM

The main disadvantages of Vue.js include: 1. The ecosystem is relatively new, and third-party libraries and tools are not as rich as other frameworks; 2. The learning curve becomes steep in complex functions; 3. Community support and resources are not as extensive as React and Angular; 4. Performance problems may be encountered in large applications; 5. Version upgrades and compatibility challenges are greater.

Netflix: Unveiling Its Frontend FrameworksNetflix: Unveiling Its Frontend FrameworksMay 04, 2025 am 12:16 AM

Netflix uses React as its front-end framework. 1.React's component development and virtual DOM mechanism improve performance and development efficiency. 2. Use Webpack and Babel to optimize code construction and deployment. 3. Use code segmentation, server-side rendering and caching strategies for performance optimization.

Frontend Development with Vue.js: Advantages and TechniquesFrontend Development with Vue.js: Advantages and TechniquesMay 03, 2025 am 12:02 AM

Reasons for Vue.js' popularity include simplicity and easy learning, flexibility and high performance. 1) Its progressive framework design is suitable for beginners to learn step by step. 2) Component-based development improves code maintainability and team collaboration efficiency. 3) Responsive systems and virtual DOM improve rendering performance.

Vue.js vs. React: Ease of Use and Learning CurveVue.js vs. React: Ease of Use and Learning CurveMay 02, 2025 am 12:13 AM

Vue.js is easier to use and has a smooth learning curve, which is suitable for beginners; React has a steeper learning curve, but has strong flexibility, which is suitable for experienced developers. 1.Vue.js is easy to get started with through simple data binding and progressive design. 2.React requires understanding of virtual DOM and JSX, but provides higher flexibility and performance advantages.

Vue.js vs. React: Which Framework is Right for You?Vue.js vs. React: Which Framework is Right for You?May 01, 2025 am 12:21 AM

Vue.js is suitable for fast development and small projects, while React is more suitable for large and complex projects. 1.Vue.js is simple and easy to learn, suitable for rapid development and small projects. 2.React is powerful and suitable for large and complex projects. 3. The progressive features of Vue.js are suitable for gradually introducing functions. 4. React's componentized and virtual DOM performs well when dealing with complex UI and data-intensive applications.

Vue.js vs. React: A Comparative Analysis of JavaScript FrameworksVue.js vs. React: A Comparative Analysis of JavaScript FrameworksApr 30, 2025 am 12:10 AM

Vue.js and React each have their own advantages and disadvantages. When choosing, you need to comprehensively consider team skills, project size and performance requirements. 1) Vue.js is suitable for fast development and small projects, with a low learning curve, but deep nested objects can cause performance problems. 2) React is suitable for large and complex applications, with a rich ecosystem, but frequent updates may lead to performance bottlenecks.

Vue.js vs. React: Use Cases and ApplicationsVue.js vs. React: Use Cases and ApplicationsApr 29, 2025 am 12:36 AM

Vue.js is suitable for small to medium-sized projects, while React is suitable for large projects and complex application scenarios. 1) Vue.js is easy to use and is suitable for rapid prototyping and small applications. 2) React has more advantages in handling complex state management and performance optimization, and is suitable for large projects.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.