SoFunction
Updated on 2025-04-05

Summary of the advantages of vue3 and vue2

​​​​​​​ Summary:

Vue3The new version of the concept was formed in late 2018, when Vue 2 was two and a half years old. Compared with the life cycle of general software, it seems that it is not that long. Vue3 was officially launched in 2020. It has undergone major changes in source code and API, and its performance has been significantly improved, 1.2 to 2 times faster.

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, it seems that it is not that long. Vue3 was officially launched in 2020. It has undergone major changes in source code and API, and its performance has been significantly improved, 1.2 to 2 times faster.

Among them, some of the more important advantages are:

Optimization of diff algorithm:hoistStatic Static boost;cacheHandlersEvent listener cache;ssrRendering; better Ts support;Compostion API: Combination API/injection API; more advanced components; custom rendering API; on-demand compilation, smaller size ratio; supports multiple node components, etc.

Let’s talk about the advantages of vue3 in detail:

Advantage 1: Optimization of diff algorithm

The virtual dom in vue2 is a complete comparison (each node will be compared layer by layer regardless of whether it is written dead or dynamic, which wastes most of the events on comparing static nodes)

Vue3 has added static tags (patchflag) When comparing with the last virtual node, only the comparison ispatch flagnode (the node where the dynamic data is located); the specific content to be compared with the current node can be obtained through 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 tomsgAttributes, when msg changes, Vue will generate a new virtual DOM and then compare it with the old one.

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

When the view is updated, only the dynamic node part is diffed, reducing resource loss.PatchflagIt is an enumeration. The text with a value of 1 means that the element is dynamically bound, and the value of 2 means that the element isclassIt is dynamically bound.

Advantage 2: hoistStatic static boost

vue2 will be recreated and then rendered every time regardless of whether the element participates in the update. vue3 will perform static upgrades for elements that do not participate in the update, and will only be created once and can be reused directly during rendering. For example: Let's useVue 3 Template Explorer, let’s have an intuitive experience:

<div>
    <div>Co-creation1</div>
    <div>Co-creation2</div>
    <div>{{name}}</div>
</div>

Before static promotion

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

After static promotion

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 */
            ),
        ])
    )
}

From the above code we can see,_hoisted_1and_hoisted_2Two methods have been promoted to rendering functionsrender In addition, it is what we call static improvement. Through static boosting, you can avoid recreating these objects every time you render, which greatly improves rendering efficiency.

Advantage 3: cacheHandlers event listener cache

In the case, the binding event will be regenerated every time it is triggered.functionGo to update,cacheHandlers is the event cache object provided in Vue3, whencacheHandlersTurn on, an inline function will be automatically generated and a static node will be generated at the same time. When the event fires again, just call it from the cache without updating again.

By defaultonClickIt will be regarded as dynamic binding, so its changes will be tracked every time, but there is no need to track changes for the same function, just cache and reuse it.

For example:We also passedVue 3 Template Explorer, let’s take a look at the role of event listener cache:

<div>
    <div @click="todo">Do something interesting</div>
</div>

This sectionhtml After compilation, it 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 enable event listener cache:

export function render(...) {
    return (_openBlock(),_createBlock('div', null, [
            _createVNode('div',{
                    onClick:    // After turning on the monitoring                        _cache[1] || (_cache[1] = (...args) =>_ctx.todo(...args)),
                },'Do something interesting'),
        ])
    )
}

We can compare the code before and after the event listening cache. You may not understand the code after the conversion, but it doesn't matter. We only need to observe whether there are static marks. In Vue3's diff algorithm, only those with static marks will be compared and tracked.

Advantage 4: SSR Rendering

There is also SSR rendering in Vue2, but the performance improvements in SSR rendering in Vue3 are also compared to Vue2.

When there is a large amount of static content, these contents are pushed into a pure stringbuffer Inside, even if there is dynamic binding, it will sneak in through template interpolation. This will be much faster than rendering through virtual dmos.

When the static content is large enough to the order of magnitude, it will use_createStaticVNode Method generates a clientstatic node, these static nodes will be directlyinnerHtml, there is no need to create objects and then render them according to the objects.

Advantage 5: Better Ts support

vue2 is not suitable for using ts, becausevue2ofOption APIstyle.optionsIt is a simple object, while ts is a type system, object-oriented syntax. The two are a bit mismatched.

In the specific practice of vue2 combined with ts, it is necessary to use vue-class-component Strengthen the vue component, let Script support TypeScript decorator, and use vue-property-decorator to add more decorators that combine Vue characteristics. In the end, the ts component writing method is quite different from that of js component writing method.

In vue3, tailoreddefineComponentFunctions enable components to better utilize parameter type inference under ts.Composition API In the 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')
       = 9 // OK
     const result = ('') 
 }

Advantage 6: Compostion API: Combination API/injection API

The traditional web page ishtml/css/javascript(Structure/Style/Logic) Separation. Vue puts closely linked structures/styles/logics together in a componentized way, which is conducive to code maintenance.compostionapiGoing further, focus on the JS (logic) part and put logic-related code together, which is more conducive to the maintenance of the code.

What is used in the vue2 component isOption APIstyle(data/methods/mounted) to organize the code, which will disperse the logic. For example, we complete a counter function and declare variables in data.methodsDefine the response function, inmountedInitialize variables in. If you want to maintain such a function in a component with more functions and larger code volume, you need to maintain such a function indata/methods/mountedSwitch to the corresponding position repeatedly and make code changes.

In vue3, usesetupfunction. As shown belowcountRelated logic,Put them all in the file,andtodoRelated logic放到里。

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 in this way. The component must have a node and it can now be written in this way. vue will create a virtualFragmentnode.

&lt;template&gt;
&lt;div&gt;Huawei Cloud Enjoy Expert&lt;/div&gt;
&lt;div&gt;Full-stack blogger&lt;/div&gt;
&lt;/template&gt;

existSuspended-componentThe backup content will be displayed before fully rendering. If it is an asynchronous component,SuspenseYou can wait for the component to be downloaded, or perform some asynchronous operations in the settings function.

Advantage 8: Custom rendering API

Project architecture for weex (mobile cross-platform solution) andmyvue(used on mini-programs) and other renderings to different platforms are not very friendly. vue3.0 launched a custom rendering API to solve this problem. Let’s first look at the differences in the entry writing methods of vue2 and vue3.

vue2:

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

vue3:

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

Official implementation of vuecreateApp Will give it to ustemplate Mapping generates html code, but if you don't want to render to html, you have to render tocanvas When something like this is not HTML code, you need to use itCustom Renderer API To define your own render rendering generation function.

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

Use a custom rendering API, such asweexandmyvueThe problem with this kind of solution is perfectly solved. Just rewritecreateAppJust do it.

Advantage 9: Compile on demand, smaller size ratio

The size of the frame will also affect its performance. This is the only concern for web applications, because instant downloads are required 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 has a runtime size compressed to 23 KB).

In Vue 3, this is achieved by moving most global APIs and internal helpers to export to the ES module. This allows modern packaging tools to statically analyze module dependencies and remove unused export-related code. The template compiler will also generate friendlyTree-shaking Code, import the helper program for this function only when the function is actually used in the template.

Some parts of the framework will neverTree-shaking, because they are essential for any type of application. We refer to the metrics of these essential parts as benchmark sizes. Despite many new features added, the Vue 3's benchmark size is about 10 KB compressed, less than half as much as Vue 2.

Advantage 10: Supports multiple node components

Vue3 A template no longer limits multiple root nodes (on multiple root nodesAttribute Inheritance) requires explicit definitionattribute Where should it be distributed. Otherwise, the console will give a warning prompt.

In Vue 3, components now officially support multiple node components, i.e. fragments!

In , multiple components are not supported, warnings are issued when the user accidentally creates multiple components, so to fix this error, many components are wrapped in one. as follows

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

In , the component 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>

Summarize:

  • Vue is one of the most popular front-end frameworks in China. Performance improvement, 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, better support for ts is also a trend.
  • Advanced giving, exposing the underlying API and providing more advanced built-in components.
  • Combining APIs can better organize logic, encapsulate logic, and reuse logic

This is the end of this article about vue3 comparing vue2. For more information about vue3 comparing vue2, please search for my previous articles or continue browsing the related articles below. I hope you support me in the future!