What are the advantages of vue3 over vue2?

Time:2021-10-25

Summary:The concept of the new version of vue3 was formed at the end of 2018, when Vue 2 was two and a half years old. Compared with the life cycle of general software, this does not seem to be that long. Vue3 was officially launched in 2020. There are great changes in source code and API, and the performance has been significantly improved, which is 1.2 ~ 2 times faster than vue2. X.

This article is shared from Huawei cloud community《[cloud resident co creation] ten advantages of vue3 over vue2》, author: Hai Yong.

The concept of the new version of vue3 was formed at the end of 2018, when Vue 2 was two and a half years old. Compared with the life cycle of general software, this does not seem to be that long. Vue3 was officially launched in 2020. There are great changes in source code and API, and the performance has been significantly improved, which is 1.2 ~ 2 times faster than vue2. X.

Some of the more important advantages are:

Optimization of diff algorithm; Hoiststatic static lifting; Cachehandlers event listener cache; SSR rendering; Better TS support; Composition API: composition API / injection API; More advanced components; Custom rendering API; Compile on demand, smaller than vue2. X; Support multiple root node components, etc. Let’s talk about the advantages of vue3:

Advantage 1: optimization of diff algorithm

The virtual DOM in vue2 is a full comparison (each node, whether dead or dynamic, will be compared layer by layer, which wastes most of the events on the static node)

Vue3 adds a static flag. When comparing with the last virtual node, only the nodes with the patch flag (the node where the dynamic data is located) are compared; You can know the specific content to be compared by the current node through the flag information.

For example, the following template contains a div, which contains three paragraphs. The first two paragraphs are static and fixed, while the content of the third paragraph is bound to the MSG attribute. When the MSG changes, Vue will generate a new virtual Dom and compare it with the old one.

<div>
 <p>Cloud resident co creation</p>
 <p>How to evaluate vue3</p>
 <p>{{msg}}</p>
</div>

When the view is updated, only the diff operation is performed on the dynamic nodes, which reduces the loss of resources. Patchflag is an enumeration. 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 boost

Vue2 no matter whether the element participates in the update or not, it is recreated and then rendered each time.

Vue3 for elements that do not participate in the update, they will be statically promoted and will only be created once. They can be reused directly during rendering.
For example, let’s use Vue 3 template explorer to intuitively experience:

<div>
    < div > co creation 1 < / div >
    < div > co creation 2 < / div >
    <div>{{name}}</div>
</div>

Before static lifting

export function render(...) {
    return (
        _openBlock(),
        _createBlock('div', null, [
            _ Createvnode ('div ', null,' co creation 1 '),
            _ Createvnode ('div ', null,' co creation 2 '),
            _createVNode(
                'div',
                null,
                _toDisplayString(_ctx.name),
                1 /* TEXT */
            ),
        ])
    )
}

After static lifting

const _hoisted_1 = /*#__PURE__*/ _createVNode(
    'div',
    null,
    'Create 1',
    -1 /* HOISTED */
)
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 */
            ),
        ])
    )
}

As we can see from the above code_ hoisted_ 1 and_ hoisted_ 2. The two methods are promoted outside the rendering function render, which is what we call static promotion. Through static promotion, you can avoid re creating these objects every time you render, which greatly improves the rendering efficiency.

Advantage 3: cachehandlers event listener cache

In vue2. X, every time a binding event is triggered, a new function must be regenerated to update. Cachehandlers is the event cache object provided in vue3. When cachehandlers is enabled, an inline function and a static node will be automatically generated. When the event is triggered again, it needs to be invoked from the cache without updating it again.

By default, onclick will be regarded as dynamic binding, so it will track its changes every time, but it is not necessary to track the changes of the same function. It can be directly cached and reused.

For example, let’s take a look at the role of event listener caching through Vue 3 template Explorer:

<div>
    < div @ Click = "todo" > do something interesting < / div >
</div>

After compilation, this HTML segment becomes our following structure (event listening cache is not enabled):

export function render(...) {
    return (_openBlock(),_createBlock('div', null, [
            _ Createvnode ('div ', {onclick: _ctx. Todo},' do something interesting ', 8 / * props * /,
                ['onClick']),
        ])
    )
}

When we turn on the event listener cache:

export function render(...) {
    return (_openBlock(),_createBlock('div', null, [
            _createVNode('div',{
                    Onclick: // after listening is enabled
                        _cache[1] || (_cache[1] = (...args) =>_ctx.todo(...args)),
                }, 'do something interesting'),
        ])
    )
}

We can compare the code before and after opening the event monitoring cache. You may not understand the converted code, but it doesn’t matter. We just need to observe whether there are static tags. In vue3’s diff algorithm, only those with static tags will be compared and tracked.

Advantage 4: SSR rendering

There is also SSR rendering in vue2, but the performance of SSR rendering in vue3 is also improved compared with vue2.

When there is a large amount of static content, it will be pushed into a buffer as a pure string. Even if there is a dynamic binding, it will sneak in through template interpolation. This will be much faster than rendering through virtual DMO.

When the static content is up to an order of magnitude, it will be used_ The createstaticvnode method generates a static node on the client side. These static nodes will be directly innerHTML, so there is no need to create objects, and then render according to the objects.

Advantage 5: better TS support

Vue2 is not suitable for TS because of its option API style. Options is a simple object, while TS is a type system, object-oriented syntax. The two don’t match.

In the specific practice of vue2 combined with TS, Vue class component should be used to strengthen Vue components, let script support typescript decorators, and Vue property decorator should be used to add more decorators combined with Vue features. Finally, the component writing method of TS is quite different from that of JS.

In vue3, the definecomponent function is customized to make better use of parameter type inference under ts. In the composition api code style, the representative APIs are ref and reactive, which also support type declaration.

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('') 
 }

Advantage 6: composition API: composition API / injection API

Traditional web pages are separated by HTML / CSS / JavaScript (structure / style / logic). Vue puts the closely related structure / style / logic together in a component way, which is conducive to code maintenance. The composition API goes further, focusing on the JS (logic) part and putting the logic related code together, which is more conducive to code maintenance.

In the vue2 component, the code is organized in the option API style (data / methods / mounted), which will disperse the logic. For example, we complete a counter function, declare variables in data, define response functions in methods, and initialize variables in mounted. If we are in a component with more functions and a large amount of code, To maintain such a function, you need to repeatedly switch to the corresponding location in data / methods / mounted, and then make code changes.

In vue3, the setup function is used. As shown below, the logic related to count is put into the counter.js file, and the logic related to todo is put 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,
}

Advantage 7: more advanced components

Vue2 is not allowed to be written like this. The component must have a following node. It can be written like this now. Vue will create a virtual fragment node for us.

<template>
< div > Huawei cloud sharing expert < / div >
< div > full stack blogger < / div >
</template>

The alternate content is displayed before the suspended component is fully rendered. If it is an asynchronous component, suspend can wait for the component to be downloaded, or perform some asynchronous operations in the setting function.

Advantage 8: custom rendering API
Vue2. X project architecture is not very friendly for rendering to different platforms such as weex (mobile end cross platform scheme) and myvue (used on applets). Vue3.0 has launched a custom rendering API to solve this problem. Let’s first look at the differences between vue2 and vue3.

vue2

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

vue3

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

The createapp officially implemented by Vue will generate HTML code for our template mapping, but if you don’t want to render to HTML, but to render to non HTML code such as canvas, you need to use the custom renderer API to define your own render rendering generation function.

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

The problem of using custom rendering APIs such as weex and myvue is perfectly solved. Just rewrite createapp.

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

The size of the frame also affects its performance. This is the only concern of a web application, because resources need to be downloaded immediately, and the application is not interactive until the browser parses the necessary JavaScript. This is especially true for single page applications. Although Vue has always been relatively lightweight (Vue 2’s runtime size is compressed to 23 KB).

In Vue 3, this is achieved by moving most of the global APIs and internal helpers to the ES module and exporting them. This enables modern packaging tools to statically analyze module dependencies and remove unused export related code. The template compiler also generates friendly tree shaking code, and imports the helper of the function only when the function is actually used in the template.

Some parts of the framework will never tree shaking because they are essential for any type of application. We call the measurement of these essential parts the benchmark size. Despite the addition of many new features, the benchmark size of Vue 3 is compressed to about 10 KB, less than half of Vue 2.

Advantage 10: support multiple root node components

Vue3 a template is no longer limited to multiple root nodes (attribute inheritance on multiple root nodes) and it is necessary to explicitly define where attributes should be distributed. Otherwise, the console will give a warning prompt.

In Vue 3, the component now officially supports multiple root node components, namely fragments!

In 2. X, multiple root components are not supported. A warning will be issued when users accidentally create multiple root components. Therefore, in order to fix this error, many components are wrapped in one. as follows

<template>
  <div>
    <header>...</header>
    <main>...</main>
    <footer>...</footer>
  </div>
</template>

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>

What I want to say at the end

Vue is one of the hottest front-end frameworks in China. The performance is improved, and the running speed is 1.2-2 times that of vue2.

Smaller volume, smaller volume vue2 to compile on demand.
Type inference, better support ts, this is also a trend.
Advanced giving exposes the underlying API and provides more advanced built-in components.
Composition API can better organize logic, encapsulate logic and reuse logic

Outlook for the future:

Technology is always new and better, and more and more enterprises have upgraded vue3;

For large projects, more and more large projects can use vue3 because they are friendly to TS;

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

Click focus to learn about Huawei cloud’s new technologies for the first time~