Introduction to the

The Vue functional component is not used by most people in the development process, and even the official document placement is obscure, but it is a good choice when we are doing performance optimization for the project. This article will provide a systematic overview of the functional component initialization process. You will learn the following:

  • What are functional components
  • The difference between a functional component and a normal component
  • vueSimilarity performance optimization points

What are functional components

A functional component is a stateless component with no data, computed, watch, or lifecycle methods. There is no this context in the component, only props passing parameters. In development, there are many components that only use props and slots, which can be distilled into functional components. To borrow from the official website demo, the simplest functional components are as follows:

VueComponent ('my-component', {functional: true, Props: {// Props: {//... }, // to make up for the missing instance // provide a second argument as the context render: function (createElement, context) {//... }})

The difference between a functional component and a normal component

Component instantiation process is roughly divided into four steps: state initialization -> template compilation -> generation of VNode -> conversion to real DOM. Next, compare the common configuration items for normal and functional components to see how they differ.

Function point name Common components Functional component describe
vm Y N Component scope
hooks Y N Lifecycle hooks
data Y N Data object declaration
computed Y N Calculate attribute
watch Y N The listener
props Y Y attribute
children Y Y An array of vNode children
slots Y Y A function that returns an object containing all slots
scopedSlots Y Y The object of the scoped slot
injections Y Y Dependency injection
listeners Y Y Event listeners
parent Y Y A reference to the parent component

As you can see from the above table, the biggest difference between normal and functional components is that functional components have no independent scope and no responsive data declaration. There is no independent scope, which has the following advantages:

  1. No component instantiation (new vnode.com ponentOptions Ctor (options), functional component to get VNode is only the ordinary function call

    • No copies of public properties, methods
    • Life-free hook calls
  2. The functional component is mounted directly into the parent component, shortening the first render, diff update path

    • Functional components are generated in the parent componentVNode, a functional componentrenderThe method will be called, generatedVNodeMount to the parent componentchildren,patchStages can be directly converted into realityDOM, ordinary components are increateElm, go through the component initialization process.
    • diffWhen updated, a functional component is calledrender, directly create ordinaryVNode, while a normal component is createdVNodeIs the one that contains the component scope,diffThere are additional calls to the operationupdateChildComponentUpdate properties, custom events, etc., and the call link will be long.

VUE performance optimization points

The performance benefits of functional components come in the form of shorter rendering paths, similar to browser redraw reflux, and reduced component nesting levels, which can reduce time complexity.

No matter what kind of performance optimization can be done from the code level, is undoubtedly the least cost, although sometimes the effect is not very obvious, but many a little makes a mickle. In VUE, there are a number of points similar to the above that can improve the efficiency of code execution.

Reasonable statementdataIn the data, ensuredataDeclaration data is required in the

Many times there is data that does not need to be declared in Data, such as data that needs to be shared within a component but does not need to be processed in a reactive manner. Data objects are declared depth-first with Object.defineProperty, and arrays are also intercepted with base operation methods. Unnecessary declarations can lead to meaningless data hijacking.

The rational use ofcomputedwithwatch

The main difference between computed and watch is that computed is lazily loaded. Lazy loading is mainly manifested in two aspects:

  1. When the dependency state changes, it does not trigger immediately, just changes the current stateWatcherThe instancedirtyAttribute values fortrue
  2. When an operation is taken on a computed property value, if and only ifwatcher.dirty === trueBefore the calculation is triggered

The above two features can avoid some unnecessary code execution, the specific code is as follows:

// src\core\instance\state.js function createComputedGetter (key) { return function computedGetter () { // Const watcher = this._computedWatchers && this._computedWatchers[key] if (watcher) {// Watcher's update method is called with dirty set to true if (watcher.dirty) {// Call the get method when, Evaluate ()} if (dep.target) {watcher.depend()} return watcher.value}}} // SRC \core\observer\watcher.js update () {// computed watcher lazy === true if (this.lazy) {// mark whether the lazy execution is executable, } else if (this.sync) {// Synchronize this.run()} else {// Put the current watcher into the watcher queue queueWatcher(this) } }

V -for binding key value

The purpose of defining the key value in the V-for loop is to find the Diff comparison node accurately and avoid some meaningless comparisons.

Normal diff: Starting from the beginning to the end, the new and new sections are compared by nodding to the end respectively, and the cursor is moved to the middle. The diff process ends if and only if a node traverses the end

Diff with key value: A hash table is maintained according to the key value, and the updated target node is accurately positioned in each cycle. The diff process ends when and only when a node traversal is completed

thinking

Many of the performance improvements in Vue are in shortening the code execution path, especially when there is a lot of computing logic, and the performance gains are visible. In the actual development, there are many scenarios can use this kind of optimization method, take the simplest example, keyword highlighting matching. To do this, you need the following steps:

  1. Get the matching keyword and format the keyword (escaping the meaningful string in the regular expression)
  2. Dynamically generate matching regular expressions
  3. Follow the regular expressionreplaceoperation

In some cases, we can skip the first or second step and simply execute the third step, since the input keywords may be the same, so we can cache the string and the regular expression in the Map, and the next time we match, if there is a cache, we can simply pull it out of the cache.

Vue template compilation is used in this feature, each time will compile the template string as the key value, render method as the value, cache, if the same template, you can skip the compilation process, bring a certain performance improvement.

summary

To develop good coding habits, for personal ability, is also a good improvement.