Abstract: The idea for the new version of Vue3 took shape in late 2018, when Vue 2 was two and a half years old. Compared with the life cycle of general software, Vue3 was officially launched in 2020, with major changes in source code and API, and significantly improved performance, 1.2~2 times faster than Vue2. X.

This article is from Huawei cloud community “[Cloud resident Create Altogether] Ten advantages of VUE3 compared with VUE2”, author: Hai Yong.

The idea for the new version of Vue3 took shape in late 2018, when Vue 2 was two and a half years old. Compared with the life cycle of general software, Vue3 was officially launched in 2020, with major changes in source code and API, and significantly improved performance, 1.2~2 times faster than Vue2. X.

Some of the more important advantages are:

Diff algorithm optimization; hoistStatic static promotion; CacheHandlers Event listener cache; SSR rendering; Better Ts support; Compostion API/ injection API; More advanced components; Custom render API; Compiled on demand, smaller than vue2. X; Multi-node components are supported.

Let’s talk about the advantages of VUE3 in detail.

Advantage 1: optimization of diff algorithm

The virtual DOM in VUe2 is a full comparison (each node, both dead and dynamic, is compared layer by layer, wasting most of the events on comparing static nodes)

Vue3 added patchFlag. Compared with the last virtual node, only the node with patchflag (the node where the dynamic data resides) is compared. You can obtain the specific content to be compared on the current node through flag information.

For example, the following template contains a div containing three paragraphs. The first two paragraphs are statically fixed, while the content of the third paragraph is bound to the MSG attribute. When MSG changes, Vue generates a new virtual DOM and compares it with the old one.

The < div > < p > to create a cloud < / p > < p > how to evaluate vue3 < / p > < p > {{MSG}} < / p > < / div >Copy the code

When the view is updated, only the dynamic node part is diff operation, reducing the consumption of resources. Patchflag is an enumeration where a value of 1 means that the text of the element is dynamically bound and a value of 2 means that the class of the element is dynamically bound.

Advantage 2: hoistStatic Static promotion

Vue2 recreates and renders elements each time, whether or not they participate in updates. Vue3 does static promotion for non-updated elements, which are created only once and reused during rendering. For example: Vue 3 Template Explorer

The < div > < div > create 1 < / div > < div > create 2 < / div > < div > {{name}} < / div > < / div >Copy the code

Before static lift

export function render(...) {return (_openBlock(), _createBlock('div', null, _createVNode('div', null, 'create1 '), _createVNode('div', null,' create1 '), 'create 2'), _createVNode (' div ', null, _toDisplayString (_ctx. Name), 1 TEXT / * * /),]))}Copy the code

After static lift

Const _hoisted_1 = / * # __PURE__ * / _createVNode (' div ', null, 'create 1', HOISTED 1 / * * /) const _hoisted_2 = / * # __PURE__ * / _createVNode (' div ', null, 'create 2', -1 /* HOISTED */ ) export function render(...) { return ( _openBlock(), _createBlock('div', null, [ _hoisted_1, _hoisted_2, _createVNode( 'div', null, _toDisplayString(_ctx.name), 1 /* TEXT */ ), ]) ) }Copy the code

The _hoisted_1 and _hoisted_2 methods have been promoted beyond render. Static promotion greatly improves rendering efficiency by eliminating the need to recreate these objects every time you render.

Benefit 3: cacheHandlers event listener cache

In Vue2. X, each time a binding event is triggered, a new function is generated to update it. CacheHandlers are the event caching object provided in Vue3. When cacheHandlers are enabled, an inline function is automatically generated along with a static node. When the event fires again, it is simply called from the cache, without needing to update again.

By default, onClick is treated as a dynamic binding, so it is tracked every time it changes, but the same function does not need to be tracked, just cached and reused.

For example, here’s a look at the event listener cache using the Vue 3 Template Explorer:

<div> <div @click="todo"> Do something fun </div> </div>Copy the code

This HTML is compiled to form the following structure (with event listening caching disabled) :

export function render(...) { return (_openBlock(),_createBlock('div', null, [ _createVNode('div',{ onClick: _ctx todo}, 'do something interesting, 8 / * * / PROPS, [' onClick']),])}Copy the code

When we enable event listener caching:

export function render(...) { return (_openBlock(),_createBlock('div', null, [ _createVNode('div',{ onClick: / / open after listening _cache [1] | | (_cache [1] = (... the args) = > _ctx. Todo args (...)),}, 'do some interesting things),])}Copy the code

We can compare the code before and after the event listening cache is enabled, and the code after the conversion, you may not understand, but it doesn’t matter, we just need to observe whether there is a static mark, in Vue3 diff algorithm, only the static mark will be compared, will be traced.

Advantage 4: SSR rendering

There is ALSO SSR rendering in Vue2, but COMPARED with Vue2, SSR rendering in Vue3 also has corresponding improvement in performance.

When there is a lot of static content, it is pushed into a buffer as a string, even if there is a dynamic binding, which is sneaked in through template interpolation. This will be much faster than rendering through virtual DMO.

When static content is an order of magnitude larger, the _createStaticVNode method is used to generate a static node on the client side. These static nodes are innerHtml directly, eliminating the need to create objects and render from them.

Advantage 5: Better Ts support

Vue2 is not suitable for TS because of the Option API style of VUe2. Options is a simple object, while TS is a type system, object-oriented syntax. There’s a bit of a mismatch.

In the implementation of VUE2 with TS, vUE components should be enhanced with vuE-class-component, Script should support TypeScript decorators, and vue-property-decorator should be used to add more vUE decorators. In the end, the ts component writing is quite different from the JS component writing.

In VUe3, the defineComponent function is tailored to make components better use of parameter type inference under TS. Among the Composition API code styles, the typical apis are ref and Reactive, which also support type declarations.

import { defineComponent, ref } from 'vue'
const Component = defineComponent({
    props: {
        success: { type: String },
        student: {
          type: Object as PropType<Student>,
          required: true
       }
    },
    setup() {
      const year = ref(2020)
      const month = ref<string | number>('9')
      month.value = 9 // OK
     const result = year.value.split('') 
 }
Copy the code

Advantage 6: Compostion API: Compostion API/ injection API

Traditional web pages are HTML/CSS /javascript (structure/style/logic) separated. Vue makes it easier to maintain code by grouping together tightly knit structures/styles/logic in a componentized way. The compostionapi goes a step further by focusing on the JS (logic) section and putting together logically related code to make it more maintainable.

— Vue2 / data/methods/ Mounted — vue2 / data/methods/ Mounted — vue2 / vue2 / Data /methods/ Mounted — vue2 / Vue2 / Data/Methods/Mounted — vue2 / Vue2 Mounted Initializes variables in data/methods/ Mounted. If you want to maintain such a function in a component, you need to repeatedly switch data/methods/ Mounted to the corresponding position and then modify the code.

In VUe3, the setup function is used. The logic related to count as shown below goes into counter. Js, and the logic related to todo goes into todos.js.

import useCounter from './counter'
import useTodo from './todos'

setup(){
let { val, todos, addTodo } = useTodo()
let {count,add} = useCounter() 
return {
val, todos, addTodo,
count,add,
}
Copy the code

Advantage 7: More advanced components

Vue2 is not allowed to write like this, components must have a trailing node, now we can write like this, Vue will create a virtual Fragment node for us.

<template> <div> Huawei Cloud enjoy expert </div> <div> Full stack domain blogger </div> </template>Copy the code

Alternate content is displayed before the Suspended- Component is fully rendered. In the case of asynchronous components, Suspense can wait for components to be downloaded, or perform some asynchronous operations in setup functions.

Advantage 8: Custom rendering apis

The vue2.x project architecture is not friendly for rendering on different platforms such as WEEX (mobile cross-platform solution) and Myvue (small application), and vue3.0 introduced a custom rendering API to solve this problem. Let’s take a look at the differences between vue2 and VUe3.

vue2

import Vue from 'vue'
import App from './App.vue'
new Vue({ => h(App)}).$mount('#app')
Copy the code

vue3

const { createApp } from 'vue'
import App from "./src/App"
createApp(App).mount(('#app')
Copy the code

Vue createApp will generate HTML code for our template map, but if you don’t want to render to HTML, you want to render to canvas or something other than HTML, Use the Custom Renderer API to define your own render generation functions.

import { createApp } from "./runtime-render"; import App from "./src/App"; // Root component createApp(App).mount('# App ');Copy the code

Using custom rendering apis, such as Weex and MyVue, solves the problem perfectly. Just rewrite createApp.

Advantage 9: Compiled on demand, smaller than vue2. X

The size of the framework also affects its performance. This is the sole concern of a Web application, which is not interactive until the browser parses the necessary JavaScript because the resources need to be downloaded immediately. This is especially true for single-page applications. Although Vue has always been relatively lightweight (Vue 2 has a runtime size compression of 23 KB).

In Vue 3, this was achieved by moving most of the global apis and internal helpers to the ES module export. This allows modern packaging tools to statically analyze module dependencies and remove unused export-related code. The template compiler also generates friendly tree-shaking code, and the helper for this feature is imported only when it is actually used in the template.

Some parts of the framework will never be tree-shaking, because they are essential for any kind of application. We refer to these essential measurements as reference dimensions. Despite the many new features, the base size of Vue 3 is about 10 KB compressed, less than half that of Vue 2.

Advantage 10: Multiple node components are supported

Vue3 a template is no longer limited to having multiple root nodes. (Attribute inheritance on multiple root nodes) you need to explicitly define where the attributes should be distributed. Otherwise, the console will give a warning.

In Vue 3, components now officially support multi-node components, known as fragments!

In 2.x, multiple components are not supported, and a warning is issued when users accidentally create multiple components, so to fix this error, many components are wrapped in one. The following

<template> <div> <header>... </header> <main>... </main> <footer>... </footer> </div> </template>Copy the code

In 3.x, components can now have multiple root nodes! However, this does require developers to clearly define where attributes should be distributed.

<template> <header>... </header> <main v-bind="$attrs">... </main> <footer>... </footer> </template>Copy the code

The last thing I want to say

Vue is one of the hottest front-end frameworks in the country. Improved performance, running 1.2-2 times faster than vue2.

  • Smaller volume, on-demand compilation volume vue2 is smaller.

  • Type inference, better support for TS is also a trend.

  • Advanced giving exposes lower-level apis and provides more advanced built-in components.

  • Combination API, can better organize logic, packaging logic, reuse logic

A vision of the future

New technology is always better, and more and more enterprises are upgrading VUE3;

Large projects, more and more large projects can use VUE3 due to TS friendly;

As programmers, we should adapt to the market, improve our competitiveness, and provide room for salary increases.

Click to follow, the first time to learn about Huawei cloud fresh technology ~