Basis:

V-if vs. V-show:

V-show: controls the display and hiding by using display.

V-if is the component that actually renders and destroys, not reality and chant;

Use V-show for frequently switching scenarios.

keep-alive:

Cache components that need frequent switching but not frequent rendering; For example, TAB switching;

It can also be used as one of the means of vUE performance optimization;

mixin:

Advantages: Applicable to multiple components with the same logic, can use mixin, more convenient;

Disadvantages: Multiple mixins may cause naming conflicts; Variable sources are not clear, which is not conducive to reading;

Mixins and components may have many-to-many relationships, resulting in high complexity.

Computed is different from Watch

** Computed advantages: Caching, data does not change and does not recalculate; Improve performance; 六四屠杀

Watch: Observation function, asynchronous callback operation when data changes;

  • Computed: Computed attributes depend on other attribute values, and computed values are cached. Only when the dependent attribute values change, computed values will be recalculated the next time it obtains computed values.
  • Watch: No caching, more “observation” function, when the monitored data changes will perform a callback for subsequent operations; When you need to listen deeply for properties in an object, you can turn on the deep: True option to listen for each item in the object
  • Using the scenario:
    • When we need to do numerical calculations and rely on other data, we should use computed, because we can take advantage of the caching nature of computed and avoid recalculating each time we get a value.
    • Vue passes when we need to perform asynchronous or expensive operations when data changeswatchOptions provide a more general way to respond to changes in data. This approach is most useful when we need to perform asynchronous or expensive operations when data changes, limiting how often we can perform that operation and setting intermediate states until we get the final result. These are all things you can’t do with computed properties.

$nextTick:

NextTick triggers a callback after Dom update is complete;

Implementation principle:

The nextTick method uses macro and micro tasks and defines an asynchronous method. Multiple calls to nextTick queue the method, and the current queue is emptied by this asynchronous method. So this nextTick method is asynchronous;

A deferred callback is performed after the next DOM update loop ends. NextTick mainly uses macro and micro tasks. Try them separately according to the execution environment

  • Promise
  • MutationObserver
  • setImmediate
  • If none of the above fails, use setTimeout

Note: MutationObserver ()

Creates and returns a new MutationObserver that is called when the specified DOM changes.

The setImmediate() method is used to interrupt a long-running operation and run the callback function immediately after the browser completes other actions, such as events and display updates.

Defines an asynchronous method that clears the current queue by making multiple calls to nextTick to queue the method.

V – using key for:

1) Must be key, cannot be index;

2) In diff algorithm, whether sameNode is determined by tag and key;

The key is a unique token for a Vnode in a Vue. With this key, our diff operation can be more accurate and faster

  • The sameNode function a. keey === B. Keey can be compared with the sameNode function a. keey === B. So it’s more accurate.
  • Faster: Using the uniqueness of keys to generate map objects to obtain corresponding nodes, faster than traversal

3) Reduce rendering times and improve performance;

Common component communication in VUE;

The commonly used:

Parent components: props and this.$emit;

Custom events: Event. On the event. On the event. On the event. The off and event. No (need in destory life cycle, the destruction of the custom event evenet. No (need in destory life cycle, Destroy the custom event evenet.no (You need to destroy the custom event evenet.off during the DeStory life cycle)

vuex

There are roughly the following types:

Parent-child component communication

  • Event mechanism (** parent -> child props, child -> parent on, on, on, emit)
  • Get parent component instances parent, parent, parent, children
  • Ref calls a component’s property or method by getting an instance
  • Provide, inject (not recommended, commonly used when component libraries)

Sibling communication

  • EventBus is an approach that uses an empty Vue instance as the central eventBus (event hub) to trigger and listen for events, enabling communication between any component, including parent, intergenerational, and sibling components.

Vue.prototype.$bus = new Vue

  • Vuex

Cross-level component communication

  • Vuex

  • Attrs, attrs, attrs, listeners

BeforeDetory Usage scenarios:

Remove the custom event evenet.$off

Clear timer

Remove custom DOM events, such as Window Scroll, etc.

Template compilation

The template compiler generates the render function in one way, executes the render function to return VNode, and executes path and diff based on VNode. Templates must be converted to JS code process, called compiling templates;

Templates are not HTML, HTML is tag language;

For example, a list template:

// list const template = '<ul> <li v-for="item in list" :key="item.id">{{iitem.title}}</li> </ul> Using the with syntax to iterate over a list of numbers or objects, using a function, //with(this) {return _c('ul',_l((list),function(item){return _c (' li ', {key: item id} [_v (_s (item. The title))])}), 0)}; Where _c stands for createElemet _L (list) stands for target. _L = renderList copies the codeCopy the code

You can use Render instead of template in vue components;

How are vUE components rendered and updated?

It can be roughly divided into three steps: initial rendering, update process and asynchronous rendering.

First render:

1) Parse template as render function (or completed in development environment, vue-loader)

2) Trigger response mode, listen for the data property getter setter;

Render vnode,patch(elem,vnode)

Update process:

1) Modify data to fire the setter(the getter is already being listened on; Get is not triggered if a variable in data is not used in the template.)

2) Re-execute the render function to generate newVnode

3) Then patch(vnode,newVnode) (Diff algorithm in patch will calculate the minimum difference and update it to DOM)

Asynchronous rendering:

Asynchronous rendering of components is very important. Reducing DOM operations can reduce browser stress, mainly improving performance.

$nextTick asynchronous callback, DOM rendering, callback; Multiple data modifications will render only once; (The nextTick principle will)

The following content is my own understanding (xiao Bai ah, if there is inappropriate please point out) :

How does VUE listen for data changes? Object. DefineProperty Responsive principle

The core is Object.defineProperty to implement responsiveness (of course VUe3.0 uses Proxy)

It can be roughly divided into monitoring objects, deep monitoring of complex objects (observer(value), and monitoring of arrays.

Listening object core:

Function defineReactive(target,key,value) {// Core API // Observer (value) object.defineProperty (target,key, { get() { return value }, set(newValue) { if(newValue ! == value) {observer(newValue) // set newValue value = newValue // trigger updateView()}})} copy codeCopy the code

Complex object (observer(value)) situations need to be monitored in depth

Function oberver(target) {if (typeof target! = = 'object' | | target = = = null) {/ / not object or an Array of return target} / / pollution global Array prototype if (Array. IsArray (target)) { Target. _proto_ = arrProto} for (let key in target) {defineReactive(target,key,target[key])}} Copy codeCopy the code

Listen for array changes :(can’t listen for array natively, need special handling here;)

Const oldArrayProperty = array. prototype Const arrProto = object.create (oldArrayProperty); ['push', 'pop', 'shift', 'unshift', ForEach (methodName => {arrProto[methodName] = function () {updateView() // Triggers view updates oldArrayProperty[methodName].call(this, ... arguments) // Array.prototype.push.call(this, ... Arguments)}}) copy codeCopy the code

Object. DefineProperty shortcomings:

1) Depth monitoring, need to recurse to the end (how deep the source data object is, it is necessary to recurse to the deepest point in a one-time cycle), one-time calculation is relatively large

Vue. Set Vue. Delete can be added or deleted.

3) The array cannot be listened on natively, which requires special processing;

Diff algorithm process (unfinished) :

This I read a few blogs, but I still don’t understand; It took almost a day to figure it out; I suggest that you draw the diff comparison process on your hand book.

Diff, contrast, is a broad concept. ** Diff algorithm is to compare virtual nodes and return a patch object, which is used to store the different places of two nodes. Finally, messages recorded by patch are used to update Dom locally. ** In other words: Diff calls a function called Patch to compare the old and new nodes and patch the real DOM as it does so;

Compare the process

  • Peer comparison, and then child node comparison

  • First determine if one parent has children and one parent has no children (if the new child has no children, remove the old child)

  • Compare the case where both nodes have children (core diff)

  • Recursively compare child nodes;

The core Diff algorithm of Vue2 adopts the algorithm of _** double-end comparison **_, and compares the two ends of the old and new children at the same time, finds the reusable node with the help of the key value, and then carries out relevant operations. Compared with the React Diff algorithm, it can reduce the number of nodes to be moved, reduce unnecessary performance loss, and be more elegant. (Double-ended comparison, is at the same time from the two ends of the old and new children start to compare a way) diff algorithm in the double-ended comparison of the general steps, and then specific steps of each comparison suggested another special article, better understand the logic of double-ended comparison.

In the process of a comparison, a maximum of four comparisons are required:

  • 1, use oldchildrenThe firstVNodeWith the newchildrenThe firstVNodeThan, that is,oldStartVNodenewStartVNodeCompare to.
  • 2, use oldchildrenThe last oneVNodeWith the newchildrenThe last oneVNodeThan, that is,oldEndVNodenewEndVNodeThe comparison.
  • 3, use oldchildrenThe firstVNodeWith the newchildrenThe last oneVNodeThan, that is,oldStartVNodenewEndVNodeThe comparison.
  • 4, use oldchildrenThe last oneVNodeWith the newchildrenThe firstVNodeThan, that is,oldEndVNodenewStartVNodeThe comparison.

In the above four steps of comparison, we try to find reusable nodes, that is, nodes with the same key value. In the four-step comparison, if reusable nodes are found in any step, subsequent steps will be stopped. The following figure can be used to describe the four steps in a comparison process:

Diff algorithm time complexity

O(n)

Normally, the time complexity of the two Diff trees is O(n^3), but in practice, we rarely move the DOM across hierarchies, so Vue optimizates the Diff from O(N ^3) -> O(n). Only when the old and new children have multiple children nodes, the core Diff algorithm is needed to compare them at the same level.

Tree diff O (n3) :

Contains three firsts: traversing tree1; Tree2 is traversed the second time; Third, sort

Diff optimized to O(n) in Vue:

Compare only the same level, not across levels

If the tag is not the same, it will be deleted and reconstructed without depth comparison

If the tag and key are the same, they are considered the same node.

Comparative advantage of V3 and V2

Better performance

Better TS support

Better code organization

Better logical pull away

A smaller

More new features

V3.0 Proxy responsiveness principle

Vue3 uses proxy instead of ojject.defineProperty

The advantages of proxy are as follows:

Can realize deep monitoring, better performance;

Listen to add/delete properties;

Can directly listen to array changes;

How does proxy implement reactive listening? (Refer to the following code to see the code for better understanding)

  • Determine whether the current return value is Object or array, if so, then through doing the proxy method for logical processing, the realization of depth listening is in the proxy get method called recursion, the realization of depth listening; This is also the reason why the proxy response in V3 is better than the v2 response. V3 is to call recursion in the set method to achieve depth monitoring. For the multi-layer nested structure in data, the set will recurse to the specific data structure of which layer it has obtained (it will not be processed if it is not used). In v2 Object.defineProperty, it is recursive from the beginning. By default, it is all recursive at once.

  • It is possible to get/set multiple times while monitoring arrays, so how do you prevent multiple get/set triggers?

  • We can determine whether key is the property of the current proxied object target itself or whether the old value is equal to the new value. Trigger can be executed only when one of the above two conditions is met. If the old value is equal to the new value, it returns true.

How to determine whether it is new data?

  • Check in reflect.ownKeys (Target) to see if the key already exists;

What is a Vite?

Vite is a front-end packaging tool, vUE author initiated project

Development is relatively fast, and Webpack competition

Advantages: No packaging in the development environment, fast startup

Why does Vite start fast?

The development environment uses ES6 Modules, no packaging required – very fast

Production rollup is not much faster;

Vue vs. React;

With:

  • Both support componentization;
  • Both support data-driven views;
  • Both use the Vdome to manipulate the DOM;

Vision:

  • React using JSX tends to be all JS; Vue uses templates and leans towards HTML;
  • React functional programming; Vue declarative programming;
  • React is more self-reliant (it creates a more decentralized ecosystem, so it has a richer ecosystem). The vUE ecosystem is relatively complete. Vue’s routing library and state management library are supported by official maintenance and updated synchronously with the core library.