2
Abstract: Vue3 was formed at the end of 2018, when Vue 2 was already two and a half years old. Compared to the life cycle of general-purpose software, this seems to be not so long. Vue3 will be officially launched in 2020, with major changes in source code and API, and performance has been significantly improved, 1.2~2 times faster than Vue2.x.

This article is shared from the Huawei Cloud Community " [Cloud Resident Co-creation] Ten advantages of compared to vue2 1614c02d1c611b", author: Haiyong.

The concept of the new version of Vue3 was formed at the end of 2018, when Vue 2 was already two and a half years old. Compared to the life cycle of general-purpose software, this seems to be not so long. Vue3 will be officially launched in 2020, with major changes in source code and API, and performance has been significantly improved, 1.2~2 times faster than Vue2.x.

Among them, some of the more important advantages are:

Optimization of diff algorithm; hoistStatic static improvement; cacheHandlers event listener cache; ssr rendering; better Ts support; Compostion API: combination API/injection API; more advanced components; custom rendering API; on-demand compilation, volume ratio vue2.x is smaller; supports multiple root node components, etc. Let's talk about the advantages of vue3 in detail below:

Advantage 1: Optimization of diff algorithm

The virtual dom in vue2 is a full comparison (each node will be compared layer by layer, regardless of whether it is hard-coded or dynamic, which wastes most of the events in the comparison of static nodes)

Vue3 adds a new static flag (patchflag) when comparing with the last virtual node, only the node with the patch flag (the node where the dynamic data is located) is compared; the specific content of the current node to be compared can be known through the flag information.

For example: the following template contains a div, which contains three paragraphs. The first two paragraphs are statically fixed, and the content of the third paragraph is bound to the msg attribute. When the msg changes, Vue will generate The new virtual DOM is then compared with the old one.

<div>
 <p>云驻共创</p>
 <p>如何评价 vue3</p>
 <p>{{msg}}</p>
</div>

When the view is updated, the diff operation is only performed on the dynamic node part, which reduces the consumption of resources. Patchflag is an enumeration. A value of 1 means that the text of this element is dynamically bound, and a value of 2 means that the class of the element is dynamically bound.

Advantage 2: hoistStatic static promotion

Regardless of whether the element participates in the update, vue2 will be recreated and rendered every time.

For elements that do not participate in the update, vue3 will do static promotion, which will only be created once, and can be reused directly during rendering.
For example: Below we use Vue 3 Template Explorer to intuitively feel:

<div>
    <div>共创1</div>
    <div>共创2</div>
    <div>{{name}}</div>
</div>

Before static lifting

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

After static promotion

const _hoisted_1 = /*#__PURE__*/ _createVNode(
    'div',
    null,
    '共创1',
    -1 /* HOISTED */
)
const _hoisted_2 = /*#__PURE__*/ _createVNode(
    'div',
    null,
    '共创2',
    -1 /* HOISTED */
)

export function render(...) {
    return (
        _openBlock(),
        _createBlock('div', null, [
            _hoisted_1,
            _hoisted_2,
            _createVNode(
                'div',
                null,
                _toDisplayString(_ctx.name),
                1 /* TEXT */
            ),
        ])
    )
}

From the above code, we can see that the two methods _hoisted_1 and _hoisted_2 have been promoted outside the rendering function render, which is what we call static promotion. The static improvement can avoid the need to recreate these objects every time you render, which greatly improves the rendering efficiency.

Advantage 3: cacheHandlers event listener cache

In vue2.x, a new function must be regenerated every time a binding event is triggered to update. CacheHandlers are the event cache objects provided in Vue3. When cacheHandlers are turned on, an inline function will be automatically generated and a static node will be generated at the same time. When the event is triggered again, it only needs to be called from the cache, and there is no need to update it again.

By default onClick will be regarded as dynamic binding, so its changes will be tracked every time, but the same function does not need to track changes, it can be directly cached and reused.

For example: Below we also use the Vue 3 Template Explorer to take a look at the role of event listener caching:

<div>
    <div @click="todo">做点有趣的事</div>
</div>

After the html is compiled, it becomes our following structure (the event listener cache is not turned on):

export function render(...) {
    return (_openBlock(),_createBlock('div', null, [
            _createVNode('div',{ onClick: _ctx.todo}, '做点有趣的事', 8 /* PROPS */,
                ['onClick']),
        ])
    )
}

When we enable the event listener cache:

export function render(...) {
    return (_openBlock(),_createBlock('div', null, [
            _createVNode('div',{
                    onClick:    //开启监听后
                        _cache[1] || (_cache[1] = (...args) =>_ctx.todo(...args)),
                },'做点有趣的事'),
        ])
    )
}

We can compare the code before and after the event monitoring cache is turned on. You may not understand the code after the conversion, but it doesn’t matter. We only need to observe whether there are static tags. In the diff algorithm of Vue3, only those with static tags are available. Will be compared before tracking.

Advantage 4: ssr rendering

SSR rendering is also available in Vue2, but compared to Vue2, SSR rendering in Vue3 has a corresponding improvement in performance.

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

When the static content reaches an order of magnitude, the _createStaticVNode method will be used to generate a static node on the client. These static nodes will be directly innerHtml, so there is no need to create an object, and then render according to the object.

Advantage 5: better Ts support

Vue2 is not suitable for using ts because of the Option API style of vue2. Options is a simple object, and ts is a type system, object-oriented syntax. The two do not match.

In the specific practice of combining vue2 with ts, use vue-class-component to strengthen vue components, let Script support TypeScript decorators, use vue-property-decorator to add more decorators that combine Vue features, and finally make ts components The writing method is quite different from the writing method of js components.

In vue3, the defineComponent function is tailored to make the component better use parameter type inference under ts. In the composition API code style, the more representative APIs are ref and reactive, which also support type declarations well.

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: Compostion API: Combination API/Injection API

Traditional web pages are separated from html/css/javascript (structure/style/logic). Vue puts closely related structures/styles/logics together through componentization, which is conducive to code maintenance. The compostion api goes a step further, focusing on the JS (logic) part, putting logic-related codes together, which is more conducive to code maintenance.

In the components of vue2, the Option API style (data/methods/mounted) is used to organize the code, which will disperse the logic. For example, we complete a counter function. We need to declare variables in data and define responses in methods. Function, initialize variables in mounted. If you want to maintain such a function in a component with more functions and a large amount of code, you need to switch to the corresponding position in data/methods/mounted repeatedly, and then change the code .

In vue3, the setup function is used. As shown below, the logic related to count is placed in the counter.js file, and the logic related to todo is placed in 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 does not allow this to be written. The component must have a follower node. Now you can write this way. Vue will create a virtual Fragment node for us.

<template>
<div>华为云享专家</div>
<div>全栈领域博主</div>
</template>

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

Advantage 8: Custom rendering API
The vue2.x project architecture is not friendly for rendering to different platforms such as weex (mobile cross-platform solution) and myvue (used on small programs). Vue3.0 launched a custom rendering API to solve this problem. Let's first look at the difference between the entry writing of 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 canvas and other codes that are not html, then you need to use the Custom Renderer API. Define your own render rendering generation function.

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

The problem of using custom rendering APIs, such as weex and myvue, has been 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 the web application, because the resource needs to be downloaded instantly, 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 (the runtime size of Vue 2 is compressed to 23 KB).

In Vue 3, this goal was achieved by moving most of the global APIs and internal helpers to ES module exports. 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 of this function is only imported when the function is actually used in the template.

Some parts of the framework will never be Tree-shaking because they are essential for any type of application. We call the metrics for these indispensable parts the base size. Despite the addition of many new features, the baseline size of Vue 3 is approximately 10 KB after compression, which is less than half of Vue 2.

Advantage 10: Support multiple root node components

A template in Vue3 is no longer restricted to multiple root nodes. (Attribute inheritance on multiple root nodes) needs to explicitly define where the attributes should be distributed. Otherwise, the console will give a warning.

In Vue 3, components now officially support multi-root node components, namely fragments!

In 2.x, multiple root components are not supported, and a warning will be issued when the user accidentally creates multiple root components. Therefore, in order to fix this error, many components are packaged 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 the 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 most popular front-end frameworks in China. The performance is improved, and the running speed is 1.2-2 times that of vue2.

The volume is smaller, and the volume of vue2 compiled on demand is smaller.
Type inference and better support for ts is also a trend.
High-level grants expose lower-level APIs and provide more advanced built-in components.
Combining APIs can better organize logic, encapsulate logic, and reuse logic

Prospective to the future:

The newer the technology, the better, and more and more companies have upgraded vue3;

Large-scale projects, more and more large-scale projects can use vue3 due to the friendliness of TS;

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

Click to follow, and get to know the fresh technology of


华为云开发者联盟
1.4k 声望1.8k 粉丝

生于云,长于云,让开发者成为决定性力量