The difference between Vue3 and Vue2

How source code is organized

  • Rewrite in TypeScript

First of all, in order to improve the maintainability of the code, Vue3.0 abandoned the Flow type comments, and instead adopted a more strict TypeScript rewrite. Large projects recommend using typed languages, which can help us check typed problems during coding, such as passing parameters to functions. If the types do not match, there will be a corresponding type prompt. Of course, you can use JavaScript instead of TypeScript in your projects, and Vue3.0 is fully supported

  • Monorepo was used to manage the project structure

Monorepo uses a single project to manage multiple packages, putting the code of different functions into different packages to manage, so that the division of each functional module is clear, the dependencies between modules are clear, and each functional module can be tested, distributed, and used separately. We can look at the directory structure for packages in the source code:

Compilers for the compiler- DOM browser platform rely on compiler-core compiler-SFC which stands for single-file-component single-file components. Compilers that rely on compiler-core and compiler-DOM compiler-SSR server-side rendering, compiler-DOM reactivity data responsiveness systems, A lightweight runtime that handles native DOM apis and events for the browser runtime and renders the DOM into JS objects. You can run it in any JS environment, you can verify that the DOM is rendered correctly, Server_renderer (); server_renderer (); server_renderer (); server_renderer (); Template-explorer is a proprietary package that does not publish to NPM. Template-explorer is a real-time compiler component that runs in the browser and outputs the render function vue to build the full version of vUE, depending on compiler and runtime

Composition API

Although the code of Vue3.0 has been completely rewritten, more than 90% of the API is still compatible with 2.x. In addition, according to the feedback from the community, Composition API was added to solve the problem that it is difficult to split and reuse oversized components using Options API when vue2. x is developing large projects.

1. How to learn Composition API?

The best way to learn Composition API is to check the official RFC (Request For Comments). The major changes from Vue2 to Vue3 were confirmed through the RFC mechanism. First, the management made some proposals, and then collected community feedback and discussed. Final confirmation. RFC official address: github.com/vuejs/rfcs Composition API Document: v3.vuejs.org/guide/compo…

2. Design motivation for Composition API

  • Options API

Vue2. X uses the Options API, which contains an object describing component Options (data, methods, props, etc.). The Options API splits the code of the same functional logic into different Options when developing complex components.

Let’s take a look at an example

The code for this example is simple, showing the position of the mouse on the page as it moves. But when we want to add new functions such as search, we need to add our code to multiple options, which can be a bit troublesome. In addition, Options API is difficult to extract some common codes. Although we can use mixins to extract some reusable logic, there are also many problems in the use of mixins, such as naming conflicts and unclear data sources.

  • Composition API

Composition API is a new API in Vue3.0. It is a set of function-based apis that can organize component logic more flexibly.

We can rewrite this logic using the Composition API

As you can see from the above code, we have encapsulated all of the repeated functions in the useMousePosition function. When we need to use it, we just need to call it in the setup function. In this way, when we look at some logic, we only need to look at a function, instead of looking through various options.

Here’s a comparison of the Options API and Composition API:

The same color represents the same function. We can see that the same function in the Options API is split into different code blocks. When the function of a component is complex, the code of the same logic is split into different locations, and developers need to spend a certain amount of energy to organize the logic. In the Composition API, the same logic is in the same code block, which makes it easier to work with components. Of course, the Composition API is just a new set of apis added to Vue3. You can use the Options API and Composition API together to make your logic more flexible.

Performance improvement

Vue3.0 rewrites the reactive principle with Proxy and optimizes the compiler to rewrite the virtual DOM, resulting in significant improvements in rendering and update performance. Server rendering performance has also been improved two to three times.

1. Responsive system upgrade

The core of the responsivity principle in Vue2. X is Object.defineProperty. When data is initialized, it iterates through all the members and performs recursive responsivity on the data, even if you don’t use this property. In Vue3.0, Proxy Object is used to rewrite the responsive system, and the performance of Proxy itself will be better than Object.defineProperty. In addition, the Object of Proxy Proxy can intercept the operation of accessing, assigning, adding and deleting attributes. And the Proxy can listen for the index and length properties of the array. Proxy triggers the Proxy only when the object accesses a certain attribute. Instead of recursively processing all attributes in Vue2. X, Proxy can listen for dynamically added attributes by default, while Vue2. So the use of Proxy to rewrite reactive systems in Vue3.0 greatly improves the overall performance of the framework.

2. Compilation optimization

Let’s start by reviewing the Vue2. X compilation execution through a component

In Ve2. X the template is first compiled into the render function, which is usually done during build time. At compile time, static root nodes are compiled and static nodes are compiled. Then the update function of Watcher is triggered, and the patch operation of virtual DOM is finally performed. In the process of diff, all virtual DOM will be traversed and compared, and the old and new DOM will be compared through the double-pointer algorithm, and the differences will be found and updated to the real DOM. The smallest unit of rendering in Vue2. X is the component. By marking the static root node, the diff operation is optimized by skipping the static root node during diff, but the static node still needs diff, this process is not optimized. To improve performance, Vue3.0 will mark and promote all static nodes, and only need to compare the content of dynamic nodes when diff. In addition, Vue3.0 introduced the feature of Fragments, which do not require a unique root node to be placed in templates. Templates can be used to place text content or many HTML tags of the same level. However, in vscode, you need to upgrade your vetur plug-in, otherwise the compiler will report errors.

Let’s use the official Explorer plug-in to see what has been optimized for the template

The template:

Template is compiled:

In Vue3.0, if there is no root node in the outer layer of the template, a Fragment is created. The cost of operating the Fragment is very small, and the performance cost is very small compared to manipulating the DOM. We can see that static nodes such as _hoisted_1, _HOisted_2, and _hoisted_3 are promoted to the outer layer of render, so that they are created only once during page initialization, and can be directly referenced next time the view is rerendered. Such static nodes also do not participate in the diff process. In line 18 of the compiled diagram, we can see that the following comment is 9,9 is the patch-flag concept introduced in Vue3.0, which means that the current text and props are dynamic content, and the dynamic binding property recorded is id. When diff, Only dynamically bound text and ID attributes are checked for changes, which greatly improves the performance of the virtual DOM diff. In line 20, we can see that there is a cache that holds the bound function, which is cached on the first rendering and read from the cache when it is called again, thus avoiding many unnecessary updates.

3. Optimization of source volume

Vue3.0 has removed some of the less common apis, such as inline-template, filter (my personal favorite [manual dog head]), etc. Tree-shaking is even better in Vue3.0. Tree-shaking relies on ES Modules, the import and export syntax in ES6. Make the packing volume smaller. Vue3.0 was designed with tree-shaking in mind. Built-in components such as Transition and keep-live and built-in commands such as V-Model are brought in on demand. Many other Vue3.0 apis are tree-shaking, and only core modules and the ones you use are packaged, if you don’t use them, not packaged.

Vite

With the release of Vue3.0, management also released a new build tool, Vite, which does not need to be packaged in the development and test phase, but can directly run the project, greatly improving the efficiency of development. Before we move on to Vite, let’s take a look at the ES Module specification, because Vite is based on the ES Module specification. If you’re not familiar with the ES Module specification, check out the modularity development I wrote about earlier. Modern browsers basically support ES Module (IE does not support manual damn! ES Module has some features:

  • Load the module as follows
<script type="module" src="..."></script>
Copy the code
  • Supports lazy loading of modules’ scripts by default
    • Similar to the script tag set defer
    • Executed after the document has been parsed before the DOMContentLoaded event is triggered

Vite is fast because it uses ES Module directly to load modules, which can be run in development mode without packaging. In vue-CLI development mode, the project must be packaged to run.

Vite characteristics

  • Quick cold start

Since there is no packaging required, Vite can take advantage of ES Module features to quickly launch projects

  • According to the need to compile

The code is compiled on demand, so the code is compiled only when the current runtime environment needs to be loaded. You don’t have to wait for all the project files to be packaged when you start the development server, which is especially noticeable when the project is large.

  • Module hot update

Vite supports module hot update, and the performance of module hot update is independent of the total number of modules, no matter how many modules you have, HMR will always be faster.

Rollup is packaged in production using the browser’s native ES Module, without the need to use Babel to convert import to require and the corresponding helper functions. So the size of the package will be much smaller than the size of the WebPack package.

Vite creates the project

  • Vite creates a VUE project
npm init vite-app <project-name>
cd <project-name>
npm install
npm run dev
Copy the code
  • Create projects based on templates
npm init vite-app -- template react
Copy the code

When the project is up and running, we can right-click the source code and see that the Vue entry file main.js was indeed introduced via ES Module.

Let’s take a look at the console netWork request to app.vue parsing results

First, the vite-enabled server hijacks requests ending in.vue, parses.vue files into JS files, and sets the content-type of the response header to Application /javascript in order to tell the browser, Now I’m sending you a javascript script

This time app. vue is requested again, but this time with a type=template parameter. After requesting the server, The server will use the compiler- SFC module in Vue3.0 to compile the app. vue single-file component into the render function, which is basically how Vite works.