This is the 10th day of my participation in the August Text Challenge.More challenges in August

  • All changes from Vue2 to Vue3 are confirmed by VUE through THE MECHANISM of RFC. First, some official proposals are presented, and then feedback and discussion from the community are collected. Then determine whether the proposal will land.

  • Vue2’s options API implements a logic that may be required in different options (e.g., data,methods…). In complex components, we might have to keep dragging the scrollbar to find the code and then implement the logic/modify logic. It is also difficult to extract reusable code from components. Although VUe2 provides mixins for logical reuse, there are naming conflicts in mixins and data sources are unclear.

  • Composition API

    • A set of function-based apis
    • The logic of components can be organized more flexibly.

Composition API vs Options API

The Compostion API is based on functions: Where this logic is needed, just import c functions into the component. If you want to add a search logic, you can create an S function, which is required in any component, and import the S function directly. When looking at a particular logic in a component, you only need to focus on the function that implements the logic. Unlike the Options Api, the code for a query logic is scattered in different locations.Copy the code

Responsiveness of VUE2 vs responsiveness of VUE3 (performance improvement)

Responsive system upgrade

  1. Object.defineproperty in VUe2 (the heart of responsive systems)
When initialized, all members in data are iterated over, and attributes of the object are converted to GET and by definePropertysetIf the attributes in the member are still objects, the attributes of each child object need to be processed recursively. This is all done at initialization time. Even if you don't use the property, it will be processed responsively.Copy the code
  1. vue3 proxy
Proxy performance is inherently better than defineProperty, and proxy objects can intercept attribute access, assignment, deletion, etc., without having to iterate through all attributes during initialization. In addition, if there are multiple levels of nested attributes, the next level of attributes will be recursively processed only when one attribute is accessed. By default, you can use proxy to listen for dynamically added attributes and to listen for deleted attributes. You can listen for the index and length properties of an array.Copy the code

Summary: Vue3 uses proxy objects to improve the performance and functionality of responsive systems

Vue3 template compilation and VDOM patch

Vue significantly improves the performance of first I rendering and updates by optimizing the compilation process and rewriting the VDOM.

  • Vue2 compilation execution process

    1. The template needs to be compiled into the Render function, which is usually done at build time. Nodes are compiled to static nodes and static root nodes at compile time. The static root node must have a static child node.
    2. When data/ callback in data/computed/watch changes, Watcher is notified, and watcher’s update is triggered. Finally, patch operation of the virtual DOM is performed, all virtual nodes are traversed, differences are found, and then updates to the real DOM. Diff compares the entire virtual DOM, and the smallest unit of vue2 rendering is the component.
    3. Comparison:
      1. Vue2 optimizes the diff process by marking static root nodes. But static nodes still require diff, and the process is not optimized
      2. Vue3 marks and promotes all static root nodes and diff only dynamic node content.
    4. vue template explorer
    https://vue-next-template-explorer.netlify.app
    Copy the code
    1. Static root node promotion and dynamic marking (patchFlag, diff check whether the dynamic content has changed according to the flag of dynamic marking)
      1. The diFF process is performance-intensive, and VUE3 greatly improves diFF performance.
  • Caching event handlers

    • template
    <button @click="handler">Click on the</button>
    Copy the code
    • Compiled render function (with cacheHandler not enabled)
    _createVNode("button", { onClick: _ctx.handler }, "Click".8 /* PROPS */["onClick"])
    Copy the code
    • Compiled render function (with cacheHandler enabled)
    _createVNode("button", {
          onClick: _cache[1] || (_cache[1] = (. args) = >(_ctx.handler && _ctx.handler(... args))) },"Click")
    Copy the code

    When diff is performed again, it is fetched from the cache, not from _ctx (which is typically a set of component functions). There doesn’t seem to be any optimizations, but if the handler in the data changes when the handler function is fetched from the data, the page update diff will be triggered. At this point, no VDOM attributes are changed during diff because the values in the cache are fetched. Only when handler is triggered will it go to _ctx to get the latest one. So the event handler is permanently cached.

tree-shaking

  • The removal of apis such as inline-template/filter optimizes the packaging volume
  • Better tree – shaking
    • Tree-shaking relies on ESModules, the static structure of ES6 modularity syntax, import/export, and static analysis at compile time to find modules that are not introduced, making packaging smaller.
  • Transition /keep-alive and some built-in instructions in VUE3 are automatically introduced on demand.
  • Most oF the apis in Vue3 are tree-shaking.

Vite

ES Module

  • Modern browsers support esModule (IE does not)

  • Load modules in this way

    <script src="" type="module"> </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. Before the DOM tree is loaded.

vite vs vue-cli

  • Vite runs directly in development mode without packaging
    • In development mode, Vite loads modules using esModules that the browser supports natively, that is, by importing modules. Modern browsers that support ESModules load module code using script type=module, because Vite doesn’t need to package projects. So vite in development mode opens the page in seconds, whereas vue-CLI packs and starts the dev-server to open the page. Vite will start a static server that blocks browser requests. When a web page is opened, the browser will send a request to the server to obtain the corresponding module. Vite will process the browser module that is not another module, such as import XXX. Returns the compiled results to the browser.
    • Advantages:
      • Quick cold start
      • According to the need to compile
      • Hot update of modules is supported, and the speed of hot update is independent of the total number of modules
    • The production environment
      • Vite is packaged based on rollup in production
        • Package based on esModule. Babel does not convert import to require and the corresponding helper functions, so the size of the package is smaller than webpack.
  • Vue-cli projects must be packaged to run in development mode.

Vue3 knowledge

const { x, y } = useMousePoint(); // return reactive({ x,y })
Var x = position.x; var y = position.y
Reactive ({x,y}).x triggers the get method on the proxy object because x is the primary data type and assignment of the primary data type is a copy of the value.
Set reactive({x,y}) is not triggered when x is changed.
	If x in reactive({x,y}) refers to a datatype, then the value is reactive.
Copy the code

toRefs

  • ToRefs requires that the object passed in be a proxy object. Internally, a new object is created, all properties of the passed proxy object are iterated over, the values of all properties are converted to a reactive object (through ref), and the created reactive object is mounted to a new object and returned.

ref

  • For reactive data, get collects dependencies, set triggers updates, and reactive returns a proxy object if the ref parameter is an object. For primitive data, reactive creates an object with a value attribute. The value property of this object collects dependencies and triggers updates when it is get and set, respectively.

computed

  • The purpose of computed is to simplify the code in the template, cache the results, and recalculate only when the data relied on in computed property functions changes.

  • The first usage

    watch(() = > count.value+1)
    Copy the code
  • Second usage

    const count = ref(1)
    const plusCount = computed({
      get() {
        return count.value+1
      },
      set(val) {
        count.value = val-1}})Copy the code

The use of the watch

  • The three parameters of Watch
    • The first parameter: the data to listen on
    • Second argument: the function to be executed after listening for data changes. This function takes two arguments, the new value and the old value
    • Third argument: option objects, deep and immediate
  • The return value of watch
    • Unlisten the function

conclusion

The above is the design concept of VUe3 and optimization of VUe3, as well as the comparison between VIT and VUE-CLI and some knowledge of basic usage of VUe3