5. Vue interview questions

1. Are updates in Vue asynchronous or synchronous? Why?

The data is updated synchronously, the view is updated asynchronously, because if the view is updated synchronously, it will result in multiple renders wasting unnecessary performance, which is not necessary, and internally de-duplicated (re-updated values) and buffered (only updated last time).

2. What is the principle of nextTick in Vue?

Because update is asynchronous, sometimes the outside world may want to get the latest DOM element for operation after updating data. In order to achieve unified effect for users, Vue uses nextTick internally and also allows users to use nextTick. In VUE2, nextTick is compatible. Resolve ().then(), mutationObserve (), Setimmediate () mediate (), setTimeout (),vue3 nextTick ()) Use promise.resolve ().then() directly, and there is a chattering function inside nextTick to prevent users from calling nextTick multiple times

3. What is the principle of extend in Vue?

Passing in an object returns a class called VueComponent, which inherits from Vue, You can have all the methods on the Vue prototype, the incoming configuration items are merged with vue.options, the child components are registered using Vue.component(), and extend is called internally to convert the component configuration object into a class that extends from Vue

4. What is the principle of life cycle in Vue?

In the strategy mode, all hook functions are placed in an array as strings, and then external hooks are rewritten as functions when merged. Manage hook functions on a first-in, first-out basis. When external hooks are called, callHooks are triggered. Internal calls are made sequentially, and this inside the hook function is changed to an instance of Vue. The hooks in the lifecycle fire at different times

5. What is the principle of Watch in Vue?

Watcher, when the key value changes, will call the handler function corresponding to the key. In fact, writing in the watch object is the same as manually calling vm. All the handler functions in the watch object will be converted to vm. Watch actually works the same way. All the handler functions in the watch object will be converted to VM. watch. In fact, the key(expression) in watch will finally be evaluated in VM. Then, when the key value changes, Watcher will be notified to update it

6. What is the principle of computed tomography in Vue?

It’s essentially a Watcher, but it has caching, and it’s not triggered by default, it’s triggered when it’s evaluated on the page, Every key in computed is defined on the VM and the corresponding value is actually get or GET /set in Object.defineProperty. When the value of the dependency changes, it is re-executed. If the value of the dependency does not change, it is not re-executed. Returns the last value (cache)

The key in the calculated property does not collect the render Watcher, only the calculated Watcher, and all the values that depend on the calculated property have a Dep, and we should have those DEPs collect the render Watcher so that when the value of the dependency changes, the render Watcher is notified to update it

The internal cache is controlled with a dirty variable as a switch

7. What is the principle of mixins in Vue?

Vue source code added a static attribute options on Vue, the default is an empty object, when we go to call mixin function to mix the internal will merge, different attributes will apply different merge strategy, internal use of strategy mode (design mode) to solve the problem of if/else too much

Vuex /vuerouter source code uses mixin to mix beforeCreated hook, let all components have store, store, store, router/$route attributes. Mixins can be abused, resulting in unclear data sources

8. What is the use of Diff algorithm in Vue? Can you tell me more about it?

Diff algorithm adopts hierarchical approach to control the minimum change of granularity, the purpose is to reuse the old node as far as possible, only compare nodes of the same level, not cross-level comparison, vue2 source code will use the way of double Pointers to compare: The diFF algorithm will not be compared during initial mount, because diFF algorithm relies on the old and new virtual DOM. The virtual DOM will be generated only once after the first mount, and a new virtual DOM will be generated during the update. At this time, the old and new virtual DOM will be compared and updated differently

Comparison strategy:

  1. If the old and new nodes are different, a new label is created to replace the old label

  2. If the labels are the same but the text is different, the old text is replaced with the new text

  3. If the labels are the same, compare the properties and set the properties and styles

  4. Policy for comparing old nodes with children: 4-1. If the old node has children but the new node has no children, clear the children of the old node

4-2. If the new node has children and the old node has no children, add 4-3 to the new nodes. If all have children, internal will adopt the way of double pointer comparison, contrast head first, if don't, will compare the tail end, if the tail is not the same, will compare the old man and the new tail, if you are not the same, will compare old tail and head, note: these comparison will first determine whether the label, in judging whether or not the key, The advantage of determining key is to reuse the old node as much as possible. The advantage of comparing key with index is that the key does not change, while index may change, which leads to misjudgment and not reuse the old node. If these comparisons are different in the end, out-of-order comparison will be performed. Out-of-order comparison:Copy the code

For old nodes: A => B => C => D

New node: B => D => A => C => E

Make a mapping table

const obj = {A:0,B:1,C:2,D:3}

Check whether the new node exists in the mapping table. If it does, reuse it; if it does not, add it. The comparison process is as follows:

  1. For the first time:

    For old nodes: A => B => C => D

    New node: B => D => A => C => E

    Comparison B: Found exists, the result is as follows

    B => A => null => C => D

  2. The second:

    Old node: B => A => NULL => C => D

    New node: B => D => A => C => E

    D is compared and found to exist. The result is as follows

    B => D => A => null => C => null

  3. The third time

    Old node: B => D => A => NULL => C => NULL

    New node: B => D => A => C => E

    Compare A and find it exists, and the result is as follows

    B => D => A => null => null => C => null

  4. For the fourth time

    Old node: B => D => A => NULL => NULL => C => NULL

    New node: B => D => A => C => E

    C is compared and found to exist. The result is as follows

    B => D => A => C => null => null => null => null

  5. The fifth time

    Old node: B => D => A => C => NULL => NULL => NULL => NULL => NULL

    New node: B => D => A => C => E

    Compare E, find that it does not exist, create E element, result is as follows

    B => D => A => C => E => null => null => null => null

    Note: the above null is only used as a placeholder in the mapping table obj

9. How are array responses handled in Vue?

An array is handled differently than an object, which is iterated over, defining every value in it as a response, whereas an array is handled by overriding the seven methods of an array

  1. push
  2. pop
  3. unshift
  4. shift
  5. reverse
  6. sort
  7. Splice if the call the seven methods, will inform the watcher to update, if the call one of the new method, will get a new value, to see if the new value for reference types, if for reference types, will redefine into response type, and so generally don’t suggest array structure level nested too deeply, or use a large arrays freeze to do performance tuning, Arrays with nested reference types are also defined as reactive

10. Why must data be a function in Vue?

Due to the nature of JavaScript, data must exist as a function in a component, not as an object. The data in the component is written as a function, and the data is defined in the form of the return value of the function. In this way, every time the component is reused, a new data will be returned, which means that each component instance has its own private data space, and they are only responsible for the data they maintain, without causing confusion. In pure object form, all component instances share the same data, so change one all changed. When new Vue, data can be written as an object, because it generates an instance, and data on multiple new Vue instances will not be shared

11. What are the benefits of the name attribute in Vue?

Let the component record its own advantages:

  1. Easy to debug development tools, such as vue-devtools
  2. Easy to quickly find the current component in the development tool
  3. Can be used as a recursive component

12. In what life cycle do you usually send requests?

I personally prefer to send requests in Mounted.

  1. Does not block the rendering speed of the page

  2. / / Mounted {/ / select * from / / mounted; / / select * from / / mounted; / / select * from / / mounted; / / select * from / / mounted; / / select * from / / mounted. return state.a.b.c || []

Mounted is not a hook function for server rendering (created). In this case, the hook function is not mounted

13. Describe the Vue lifecycle and what can be done in each lifecycle?

There are 12 Vue life cycles, respectively

  1. beforeCreate

  2. created

  3. beforeMount

  4. mounted

  5. beforeUpdate

  6. updated

  7. beforeDestroy

  8. destroyed

  9. activated

  10. deactivated

  11. errorCaptured

The first eight are mostly used. Activated and deactivated are keep-alive hooks. ErrorCaptured is called when an error from a descendant component is captured

beforeCreate:

  1. Parent-child relationships confirmed (parent/parent/parent/children already have)
  2. Root element validation ($root)
  3. Initialize custom events such as ON/ON /on/emit/ once/once/once/off
  4. Initialize slots (slots), initialize _c function /slots), initialize _c function /slots), initialize _c function /createElement (both internally call createElement to create a virtual node).
  5. The attrs/attrs/attrs/listeners defined as reactive properties
  6. Initialize some variables on the instance, such as _isMounted,_isDestroyed,_watcher… Etc.
  7. The data is not yet proxied and not yet responsive
  8. Call the beforeCreate hook function

created:

  1. Initialize inject, inject data, the source code is a while loop, from the component itself to the parent, always find the parent component has the provide attribute, generally writing business code is not recommended, because the data source is not clear, their encapsulation component may be used, can achieve parent-grandson communication, The data is not yet responsive
  2. Initialize props, methods, data, computed, and Watch in sequence
  3. When initializing data, data is hijacked. At this time, data is divided into two types, one is an object, the other is an array. DefineReactive is defined internally with Object.defineProperty. If the value in the Object is still an Object, it is recursively defined as a response. If it’s an array, it hijacks 7 of the array’s methods: ‘push’, ‘pop’,’shift’,’unshift’,’splice’, ‘sort’, and ‘reverse’, because they all affect the original array. These 7 methods are overwritten internally. When the user calls these 7 methods, If the user uses push, unshift, or splice to add data to the array, it will retrieve the data and determine if it is an object. If it is an object, it will define the response again. Hijacked attributes have an __ob__ attribute
  4. Initialize provide, which is called if the value of provide is a function and points the internal this to the current component instance
  5. Call the created hook function

beforeMount:

  1. See if the render function is provided. If not,compileToFunction is called. CompileToFunction does three things
    1. The template is compiled into an AST syntax tree (AST is used to describe syntactic information, such as what tags are, what attributes are, etc.), and the internal re is used to match the content in the tag
    2. Code to compile the AST syntax tree into a string, for example:
      1

      Will be converted to {tag: ‘div’, attrs: [{id: ‘app’}], 1}, then compile into a string of code, such as: _c (‘ div ‘{id: “app”}, _v (1)), the code is a string

    3. ƒ anonymous(){with(this){return _c(‘div’,{id:”app”},_v(1))}}
  2. The above compiled function is the render function
  3. Call the beforeMount hook function

mounted:

  1. Create a render Watcher
  2. There are three things Watcher does:
    1. Call pushTarget to save the current watcher
    2. Calling the render function
    3. Call popTarget to delete the current watcher
  3. When the Render function is called, the value is evaluated on the current component instance, the get in Object.defineProperty is triggered, the dependencies are collected internally, deP/Watcher is bidirectionally associated, the real value is returned, and the virtual node is created internally and the page is updated
  4. Call the mounted hook function

beforeUpdate/updated:

  1. When the external world updates the data in the data, the set will be triggered. Since the dependencies were collected during the previous rendering, we will notify Watcher to update the data, and then create the virtual node again. This time, the virtual node will be diff compared to the virtual node created before, and the page will be partially updated
  2. Call the beforeUpdate hook function before locally updating the page
  3. The updated hook function is called after the page is locally updated

beforeDestroy/destroyed:

  1. When a component is unloaded, it clears bound events in the component, removes itself from children in the current parent, removes itself from children in the current component, removes itself from children in the current component, removes parent in the current component, clears watcher, and so on…
  2. Call the beforeDestroy hook function before a component is unloaded
  3. The Destroyed hook function is called after the component is uninstalled

14. What is the lifecycle execution process for parent and child components?

Initialize mount:

  1. Call the parent component’s beforeCreate function

  2. Call the parent component’s Created function

  3. Call the beforeMount function of the parent component

  4. Call the beforeCreate function for the child component

  5. Call the created function of the child component

  6. Call the beforeMount function of the child component

  7. Calls the mounted function of the child component

  8. Calls mounted of the parent component

Update:

  1. See if the updated data is in the child or the parent. If it is in the parent, only the beforeUpdate and updated functions of the parent are called, if it is in the child, only the beforeUpdate and updated functions of the child are called. This result is optimized by the DIff algorithm

  2. If the updated data is in the parent component and is passed to the child component, the update process looks like this

    1. Triggers the beforeUpdate function of the parent component
    2. Triggers the beforeUpdate function of the child component
    3. Fires the updated function for the child component
    4. Triggers the parent component’s updated function
  3. When unloading:

    If the parent component is unloaded, the process is like this

    1. Triggers the beforeDestroy function of the parent component
    2. Triggers the beforeDestroy function of the child component
    3. Trigger the child component’s Destroyed function
    4. Trigger the parent component’s Destroyed function

15. The difference between Computed and Watch

Computed: Computed attributes depend on other attribute values, and computed values are cached. Only when the dependent attribute values change, the computed values will be recalculated the next time it obtains computed values

Watch: it is more of an observation function, similar to the monitoring callback of some data. Whenever the monitored data changes, the callback will be executed for subsequent operations.

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.
  • Watch should be used when we need to perform asynchronous or expensive operations when data changes. Using the Watch option allows us to perform asynchronous operations (accessing an API), limits how often we perform that operation, and sets the intermediate state until we get the final result. These are all things you can’t do with computed properties

16. Add a property to the object/assign a subscript to the array/assign a length to the array

Because of object.defineProperty,Vue cannot detect the above changes. The solution is as follows:

  1. Vue.set
  2. vm.$set
  3. If it’s an array, there are seven ways that arrays can be overwritten
  4. You can reassign the whole thing

17. Principle of V-Model

The V-Model is used for two-way data binding

How it works: Templates are compiled into the following when they are compiled

  1. If you use v-Model on text and Textarea elements, then v-model is the syntactic sugar for the value attribute and input event (simpler)
  2. If you use v-Model on the CheckBox and radio elements, v-Model is the syntactic sugar for the Checked attribute and change event
  3. If v-model is used on the SELECT element, then v-model is the syntactic sugar for the value attribute and change event
  4. If you use v-Model on a component, v-Model is the syntactic sugar for the value attribute and input event

18. The difference between V-if and V-show

The difference between:

  1. V-if is conditional rendering, which determines whether the DOM is rendered or not depending on the conditions
  2. V-show is the display property that controls CSS properties to show/hide

Scene:

V-if is suitable for scenarios where conditions are rarely changed at runtime and do not need to be switched frequently; V-show is suitable for scenarios that require very frequent switching of conditions.

19. What is the best use of v-if and V-for priorities

V-for has a higher priority. After all data is looped through, v-IF is used to determine the performance

Solution:

  1. Data is processed by calculating properties, and then returned for rendering
  2. You can wrap a template tag around it and write v-if on the template tag

20. What are the communication methods of VUE components

  1. Props implements parent-child communication with each other

    1. Parent to child: Binds dynamic data directly to the child component, which receives and constrains types through the props property
    2. Child to parent: Binds a method to a child component that communicates with its parent by calling the method and passing in data
  2. On/ON/ON/EMIT enables parent-child communication

    The event is bound with @xxx= ‘fn’ on the child component, which fires fn via $emit

    Principle: Internally implements a set of custom events (publish-subscribe mode)

  3. The parent/parent/parent/children realize the parent-child communication, also can realize the ye sun communication

    1. $parent gets an instance of the parent component
    2. $children can get all child instances of the current component
  4. Ref implements parent-child communication

    1. Using a ref on a normal element gets a DOM element
    2. Ref is used to obtain the component instance, and ref is used to obtain the validate method of the form component when the form component in element-UI performs form verification
  5. EventBus

    On/ON/ON/EMIT is used to realize all component communication. The principle is to use the public Vue. Normally, business logic data is not transmitted in this way.

  6. Attrs/attrs/attrs/listeners for ye sun/son/every generation of communication

    1. $attrs contains all unprop-alive properties in all parent scopes, except class and style
    2. The $Listeners contain all V-On events that do not have a. Native modifier in their parent scope
  7. Provide /inject is applicable to grandparent/father-son/intergenerational communication

    1. Ancestor components provide data by providing, and child components inject data by injecting
    2. It is not recommended to use common service data because the data source is not clear
    3. It is suitable for self-encapsulation of components because the source of the data is clearly known
  8. Vuex uses any component to communicate (see 30 for details)

  9. . , etc.

21. Advantages of the virtual DOM

  1. No manual manipulation of the DOM is required
  2. Diff algorithm was used for optimization and local update
  3. Cross-platform, because the virtual DOM is essentially a JS object, it can be used in any environment that can run JS code, such as server-side rendering

22. Principle of responsive data in Vue

Vue mainly realizes responsive data through the following four steps

  1. Implement a listener that iterates over data objects, including properties of child property objects, adding setters and getters to all properties using Object.defineProperty(). So, if you assign a value to this object, it will trigger the setter, so you can listen for changes in the data
  2. Implement a parser (Compile), parse Vue template instructions, replace variables in the template with data, and then initialize render page view, bind the corresponding node of each instruction to update function, add subscribers to listen to the data, once the data changes, receive notification, call update function for data update
  3. Implement a subscriber (Watcher) : The Watcher subscriber acts as a bridge between the Observer and Compile. Its main task is to subscribe to the message of the change of attribute value in the Observer. When the message of the change of attribute value is received, the corresponding update function in the parser Compile is triggered.
  4. Implement a subscriber (Dep) : The subscriber uses a published-subscribe design pattern to collect subscriber Watcher and manage listener Observer and subscriber Watcher uniformly

23. Principle of template compilation in Vue

  1. The template is compiled into an AST syntax tree (AST is used to describe syntactic information, such as what tags are, what attributes are, etc.), and the internal re is used to match the content in the tag
  2. Code to compile the AST syntax tree into strings (codeGen), for example:
    1

    Will be converted to {tag: ‘div’, attrs: [{id: ‘app’}], 1}, then compile into a string of code, such as: _c (‘ div ‘{id: “app”}, _v (1)), the code is a string

  3. ƒ anonymous(){with(this){return _c(‘div’,{id:”app”},_v(1))}}
  4. Of course, some instructions/events are handled at compile time

24. What design patterns are used in Vue

  1. Publish subscribe mode (ON/ON/ON /emit)
  2. Singleton mode (only one Vue for the entire program)
  3. Policy mode (the lifecycle uses policy mode to call different callbacks based on different names to solve the problem of excessive if/else)
  4. Observer Model (DEP/Watcher)
  5. Proxy mode: to a certain Object to provide a proxy Object, and the proxy Object to control of the original Object reference, such as: _data while forming, Object. Defineproperty
  6. Mediator pattern: Allows different components to communicate by providing a unified interface, such as VUEX
  7. . , etc.

The principle of vue. use

Vue.use can be used to register a plug-in and provide a Vue as a parameter for the plug-in to use

Principle:

If the plugin is a function or an object, the plugin will call the install method provided by the object and pass the parameters. If the plugin is a function or an object, the plugin will call the install method provided by the object and pass the parameters. This function is called and the argument is passed in. The return value of use points to Vue without modifying this

26. The principle of vue. set

Vue. Set (target,key,value) $set (Vue.

Principle:

  1. If the target you set is an array and the key you pass is an index, something has been done internally
    1. Fix the length of the array because the length of the array may change
    2. Call the array’s splice method to update, because splice has been overwritten
    3. Returns the value
  2. If the target is an object, and the key value is existing, not new, something has been done internally
    1. Change value directly (target[key] = value), because if it already exists, it must already be responsive
    2. Returns the value
  3. If the target is an object and the key is not on the object itself, something has been done internally
    1. Call defineReactive to internally define the data as responsive with Object.defineProperty
    2. Notify Watcher to update the page
    3. Returns the value

27. The function and principle of keep-alive

The kepp-alive component is used as a cache to ensure that the component is not destroyed. It is an abstract component (it does not render a DOM element itself and does not appear in the parent component chain).

You can define three properties on this component, which are

  1. Include ==> The cache whitelist identifies which components can be cached
  2. Exclude ==> Indicates the blacklist of components that cannot be cached
  3. Max ==> Defines the maximum number of components that can be cached. If the number is exceeded, the first cached component will be eliminated and the current cached component will be put into the cache, using the LRU algorithm internally

Principle:

  1. Gets the first child component object wrapped around Keep-Alive and its component name

  2. According to the set blacklist and whitelist (if any) condition matching, decide whether to cache. Does not match and returns the component instance directly

  3. The cache Key is generated based on the component ID and tag, and the cache object is looked up to see if the component instance has been cached. If so, simply fetch the cached value and update the key’s position in this.keys

  4. Store the component instance and the key in the cache object defined in itself, and then check whether the number of instances in the cache exceeds the Max value

  5. Set the keepAlive property of the component instance to true. This step is used to render and execute the wrapped component’s hook function

Hook function call timing:

  1. Activated: used when the keep-alive component is activated. The value is determined based on the keepAlive attribute of the component instance
  2. Deactivated: Activated when the keep-alive component is disabled

28. Principles of modifiers in VUE

Like. Stop/prevent /. Lazy /. Enter, etc., these vue internal help us deal with good, let’s only care about the logic of business level

Principle:

  1. These modifiers are converted into functions that, once executed, call different functions to do the trick
  2. For example,.stop will actually call event.stopPropagation(),.prevent will actually call Event.stopPropagation (),.prevent will actually call Event.stopPropagation (), .prevent actually calls the event.preventDefault() function
  3. Return event.stopPropagation()/event.stopPropagation()/event.stopPropagation()/ event.stopPropagation()/event.preventDefault())
  4. The dom is bound to events and functions are added when the real DOM is generated

29. Principle of V-IF and V-for

V – for principle:

  1. _l(‘arr’,function(){return _c(‘div’)})
  2. When the Render function is called, a block of code is created, the renderList function is executed, and the for loop is executed
  3. If we loop through an object and the object has an iterator interface, we use a while loop internally to iterate over the object

V – if principle:

  1. String code that is processed into a ternary expression at compile time, such as flag? xx : xxx
  2. When the Render function is called, a block of code is created, the function is executed, and then the JS code is executed

30. Implementation principle of slots

Slots are classified into normal slots, named slots, and scoped slots

Function: slot as a placeholder, according to the conditions to render the corresponding tag structure, and can achieve father-son communication

Principle:

  1. Normal slots and named slots

    The parent component is rendered first, and the child component is replaced after rendering

    When the template is compiled, it is compiled into the corresponding string code, and then the corresponding slot is found and replaced

  2. Scope slot

31. Advantages of functional components

  1. Stateless, no data
  2. Anabiosis
  3. Without this
  4. High performance

32. Principle of forceUpdate

Force updates to refresh the view

How it works: Manually tell Watcher to do it

33. What can I do if VUEX refresh data is lost

There are three general solutions:

  1. The Store in Vuex accepts plugins and can be used with plug-ins such as vuex-PersistedState for persistent state
  2. Using local storage, such as: localStorage/sessionStorage, loading from localStorage in each state
  3. Each refresh sends a request that returns data

34. Vuex principle and detailed explanation

Vuex can centrally store and manage the status of all components of an application, communicate with any component, and internally implement a vUe-based responsive system

Key Concepts:

  1. State module: The data source that drives the view application, all reactive data

  2. Actions module: Actions commit mutations rather than direct state changes and can contain arbitrary asynchronous operations such as sending a request

  3. Mutations module: The status can only be changed in mutation, but not in other places. If the status is changed, vuex and DevTools cannot be monitored, which is a dangerous operation. Generally, we can turn on strict in store to make vuex store enter strict mode. Any modification of the Vuex state outside of the mutation processing function will throw an error

  4. Getters module: calculates properties

  5. Modules modules: You can split the store into modules, each with its own state, mutation, action, getter, and even nested submodules

Process description:

  1. In the page we can trigger the flow of the Actions module through the helper function (mapActions)/$dispatch, where we can send the request
  2. In the Actions module, we can trigger the flow of the Mutations module by commit, and we can pass in some data to mutation
  3. The mutations module can take that data and modify the status
  4. When the state changes, the view for the corresponding component is updated

Introduction to important apis:

  1. Auxiliary function

    1. MapState, which can be used in component computed by… MapState ([‘ XXX ‘]) to map data
    2. MapActions, available in component Methods via… MapActions ([‘ XXX ‘]) to map action functions
    3. MapMutations, which can be used in component Methods… MapMutations ([‘ XXX ‘]) to map the mutation function
    4. MapGetters, available in component computed by… MapGetters ([XXX]) to map calculated attribute functions
  2. replaceState

    Effect: Replaces the root state of the store

  3. RegisterModule is used to dynamically register a module

  4. createNamespacedHelpers

    Function: returns the corresponding helper function based on the namespace (very common)

Plug-ins in Vuex:

Vuex’s store accepts the plugins option, which is an array that accepts a function as an argument in the array, either to listen for mutation (for external data persistence, logging, or debugging) or to commit mutation

Principle:

An install method and Store class and helper functions are exposed inside the plug-in

  1. The install method

    Mixin mixes the beforeCreate hook with vue. mixin, internally giving each component a $store option with a value of store instance

  2. Store the class

    1. Recursive loop formatting modules, mainly for recording parent-child relationships and registering modules
    2. Recursive cyclic module installation is mainly to tell the state of the child module to the corresponding parent module, but also to handle the path stitching of namespace
    3. Define the key in the getters module into a container via Object.defineProperty
    4. New Vue defines the module’s state and getters to the data object’s $$state and computed, respectively
    5. In Vue, if an object’s attribute name starts with $or _, it will not be proxied to the VM. It will only be proxied to the first layer, _data
    6. When we get the state, the property accessor is triggered, internally returning this._vm._data.$$state
  3. Auxiliary function

    1. $$store. State [stateName]; this.$store. State [stateName]; Expand this object

35. Vue-router principle and detailed explanation

Introduction: Vue Router is a routing manager that makes it easy to build single-page applications and internally implement responsive systems based on Vue

Mode:

  1. Hash mode -> The URL hash value is used for routing, which is compatible but not beautiful. The server cannot obtain the hash value and does not cause 404 refresh problems
  2. There is no 404 problem in the development environment, because vue-router has already done it for us
  3. Abstract mode — all JavaScript runtime environments are supported. If hash and history browsers do not support this mode, routing is automatically forced into this mode

Properties:

  1. $route ==> Active route information object, including path, params, query, matched, name… Attributes such as
  2. $router ==> Route instance, including route push/replace/go… Methods such as

Life cycle hook (Navigation Guard):

  1. Global front-guard (router.beforeeach), most used in projects

    There are three parameters

    1. To –> Route object to be entered
    2. From –> Route object to leave
    3. Next –> Whether to jump To specify a path or the next route object, must be called
  2. Global resolution guard (router.beforeresolve)

    Similar to the global front-guard, the difference is that the parse guard is called before the navigation is confirmed and after all the intra-component guards and asynchronous routing components have been parsed

  3. Global afterhook (router.aftereach)

    A hook that is triggered after a route jump and takes two arguments

    1. To –> Route object to be entered
    2. From –> Route object to leave
  4. Route Exclusive guard (provide beforeEnter in route configuration options)

    There are to, from, and next parameters

  5. Components of guard (defined in the component beforeRouteEnter/beforeRouteUpdate/beforeRouteLeave)

    1. BeforeRouteEnter –> Called until the corresponding route to render the component is confirmed. Cannot get component instance this because the component instance has not yet been created
    2. BeforeRouteUpdate –> Called when the current route has changed but the component is being reused, you can access the component instance this
    3. BeforeRouteLeave –> called when leaving the corresponding route of the component, which can access the component instance this

Important Api:

  1. Router-link: indicates a forward route with the following attributes:

    1. To: indicates the route address to be jumped. By default, push is used to jump
    2. Tag: By default, router-link renders an A tag with the correct link. You can use the tag attribute to generate other tags
    3. Replace: The replace method is called to jump
    4. Exact: Enables the strict mode. The default mode is fuzzy matching
    5. . , etc.
  2. Router-view: indicates the view component matched by the rendering path. The attributes are as follows

    Name –> Named view, can display multiple views at the same time (level), rather than nested display, the default is default, you can provide the components option in the route configuration options to distinguish

  3. Router. AddRoutes (deprecated)

  4. Router. addRoute: dynamically adds a route. The parameters are as follows:

    1. ParentName: Indicates the name of the parent route. This parameter is optional. Add a new routing rule record as the child route of the existing route
    2. Route: Indicates the route object. If the name of an existing route has the same name, it overwrites the route object
  5. router.push/router.replace/router.go/router.back/router.forward

    Dynamically navigate to a new URL

Dynamic routing:

  1. Scene: There is oneUserComponent that is used to render for all users with different ids
  2. Syntax: {path: ‘/user/:id’, Component: user}
  3. When a route is matched, the value of the colons is mapped to this.$route.params. Params has an ID attribute, and the value of the id is matched, e.g. /user/1, so the id value is 1

Match any route/match a route with a specified start:

  1. Scenario: The user enters a random route in the address bar, we should return a 404 component
  2. Syntax: {path:’*’, Component: 404Component} / {path:’/user-*’,component: 404Component}
  3. First, it can match any route, which is usually placed at the bottom of the route configuration. Second, it can match any route starting with /user-
  4. Principle: Path-to-regexp is used internally as a path matching engine, which translates our path configuration into the corresponding re to match the path

Navigation:

  1. Declarative navigation:

  2. Programmatic navigation: router.push/replace, etc

  3. Programmatic/declarative navigation can be written in the following format:

    1. String: router.push(‘home’)

    2. Router.push ({path: ‘home’})

    3. Router.push ({name: ‘user’, params: {userId: ‘123’}}), carries the params parameter, /user/123 in the address bar

    4. Router.push ({path: ‘register’, query: {plan: ‘private’}}); /register? plan=private

    5. Note: If path is provided, params is ignored and Query is fine

      Router.push ({name: ‘user’, params: {userId},query:{plan: ‘private’}}) or the router. Push ({path: / user / ${username}? plan=private })

Routing component parameters:

Components and routes are decoupled using props, which can be written in three modes

  1. The Boolean model

    In a single route option configuration: {path: ‘/user/:id’, Component: user, props: true}

    In the corresponding User component: props: [‘id’], the value of id is determined by the params parameter passed by the User

  2. Object mode (static route parameters are useful)

    In a single route option configuration: {path: ‘/user’, Component: user, props: {ID :12345}}

    In the corresponding User component: props: [‘id’], the id value is 12345

  3. The function mode

    In a single route option configuration, for example {path: ‘/user/:id’, Component: user, props: route => ({params: route.params.id ,query:route.query.xxx})}

    For the corresponding User component: props:[‘params’,’params’

Principle:

As with Vuex, the VueRouter class and a static method of Install are exposed internally

  1. The install method
    1. Mixin uses a beforeCreate hook to provide all components with a **_routerRoot attribute with a Vue instance and a _route attribute with a response attribute with a curre value using the vue.util. DefineReactive ** method Nt (Routing Information Object)
    2. Add router and Router and Router and route attributes to the prototype of Vue using object.defineProperty. Router returns the route instance,router returns the route instance, and route returns the current property
    3. Vue.com Ponent defines two global components, router-Link and router-View, which are functional components
  2. VueRouter class
    1. The default routing mode is hash
    2. We created a matcher for recursively flattening routing data, stitching paths, confirming parent-child relationships, initializing some parameters, and adding the match and addRoute methods. The principle of addRoutes is to create a matcher again, flattening the old route data as the initial value
    3. The strategy pattern is used to generate different classes according to different patterns, such as HashHistory in Hash mode and HTML5History in history mode. There are some common methods above them, such as push/replace, which are extracted into their parent BaseHistory class
    4. Internal core method for handling path jumps: transtionTo
    5. History mode listens for the Hashchange event, which is triggered when the path changes and transtionTo is re-executed
    6. Hash mode determines whether the browser is compatible with hashchange events, and listens for popState events if not
    7. TranstionTo does a path match, finds all the matches, and then renders from a router-view. Router-view identifies the component to be rendered by adding a routerView attribute to the tag ($vNode gets the component tag). A depth variable is internally maintained to prevent rendering loops
    8. Jumps are implemented through the browser history API, such as pushState and replacEstate
    9. Route scrolling is implemented through window.scrollto

36. Principle of V-lazyload

Provide install method, inside the method to find the scrolling parent element, and then bind the event, determine whether the current need to display, if within the visual area, the default display, other first do not load, slide to the specified position for loading, if the lazy loading does not need to be repeatedly loaded, The interior is controlled by a loaded variable

37. MVVM understanding? And MVC

So let’s start with m, V, vm

M: Model (local data and data in the database)

V: View (the view the user sees)

Vm: ViewModel (an instance object of a Vue that separates the state of the View from the behavior of the user into an abstraction and only cares about data and business processing, not how the View handles data)

MVC:

C: Controller (controller)

The traditional MVC architecture typically uses controllers to update the model, and the view retrieves data from the model to render. When the user has input, the controller updates the model and notifies the view to update it. But one big drawback of MVC is that the controller takes on too much responsibility, and as the project gets more complex, the code in the controller gets more bloated, leading to bad maintenance

38. React vs. Vue

Thing in common:

  1. The use of Virtual DOM
  2. Responsive and componentized view components are provided
  3. Keep the focus on the core library and leave other functions such as routing and global state management to the relevant libraries

Difference:

  1. React learning is more expensive and requires knowledge of JSX and ES6 because many of the examples use these grammars, whereas Vue can build simple applications in a fraction of the time it takes to read the guide
  2. Optimization-wise, React needs to be used everywhere possible in order to avoid unnecessary re-rendering of child componentsPureComponentOr manuallyshouldComponentUpdateVue is automatically tracked during rendering, so the system knows exactly which components really need to be rerendered
  3. Component uninstallation is different. In Vue, component uninstallation kills the component instance and the page still exists. In React, the entire page is uninstalled
  4. Diff algorithm is different. Vue uses dual Pointers for comparison, while React uses different strategies for comparison

39. Performance optimization in Vue

  1. Don’t be too deep in the data hierarchy, and set up responsive data properly (because of internal recursion)
  2. Cache the results of values when using data, don’t value them too often (because of get, perform some code)
  3. Set the key property properly. If it is only used for rendering, use index. If it involves add/add etc., use unique identifier as key because internal diff algorithm is optimized for comparison
  4. V-show and V-IF options
  5. Control component granularity, since Vue is component-level updates, each component has a rendering Watcher
  6. The use of functional components, reduce the compilation layer processing, low overhead
  7. Use asynchronous (lazy loading) components with webpack’s subcontract capabilities, syntax: () => import(‘ XXX ‘)
  8. Use keep-alive components properly to prevent multiple destruction/creation of components
  9. You can use strategies like virtual scrolling
  10. Package optimization, mainly with Webpack
  11. For some data that is just for display, you can use Object.frezz to freeze it. Once frozen, it cannot be modified

6. React Interview questions (To be updated)

1. Tell me what you think of the event mechanism in React

Events in React are not actually bound to the corresponding REAL DOM. Instead, all events are bound to the Document in a unified way through the event proxy. Not only does this reduce memory consumption, but it also provides uniform subscription and removal of events when a component is mounted and destroyed. Also, the events that bubble up to the document are not native browser events, but composite events implemented by React itself. So event. stopPropagation is not valid if we don’t want the event to bubble, event.preventDefault should be called instead

2. Communication mode in React

First of all, there are several ways of communication

  1. Parent-child communication

    The most common parent-child communication implementations are the ways in which the props pass data to the child component, or the child passes data to the parent component by calling functions passed by the parent component

  2. Sibling communication

    State and event functions can be managed through a common parent component

  3. Communicate across multiple layers of components

    Context can be created using react. createContext. This instance object contains two components,Provider and Consumer. The Provider is wrapped around the party that needs data. The Consumer component can read state data in two ways, 1. Static contextTypes can be used to declare data to be used, 2. Static can be used to receive data from a function. Static can be used to receive data from a function. Static can be used to receive data from a function, while functions can be used to receive data from a function.

  4. Arbitrary component communication

    Redux or Pubsub to achieve an effect of arbitrary component communication

    First of all, Redux is a centralized management scheme of state data, which is divided into three modules, namely store module, Actions module and Reducers module. Store module is mainly used for centralized management of state data, actions module is mainly used to create the factory function module of action objects. Generally divided into synchronous action/ asynchronous action, reducers module is mainly used to generate the latest state data according to the previous state data and type type and automatically send it to the store object. Once the store receives the latest state, it will immediately trigger the subscribe method in the store. Subscribe method has a listener callback function, this callback function is automatically triggered as soon as the updated state data, thus re-rendering the component, the page can display the latest state page, in fact, this process is dependent on the one-way data flow principle, the three principles of Redux are divided into 3, 1. Unidirectional data flow, 2. State is read-only, 3. Pure functions are used to modify state. The so-called unidirectional data flow is nothing more than interactive effect of user operation view layer, which will trigger action invocation. The component is rerendered so that the user can see the latest status page, and state is read-only: The only way to change state is to trigger an action, which ensures that neither views nor network requests can change state directly, instead they can only express the intent to change it. Finally, pure functions mean that there is no uncertainty about something like random numbers, dates, etc

    PubSub is also a kind of communication way between components can be arbitrary components, it is a public library, itself is not react in a way, it is divided into the issuer and subscribers, the issuer can pass in the appropriate message name and message content, subscribers and into the appropriate message name and callback function, once the message content changes, The callback function is triggered to retrieve the latest message content for communication between components

3. Performance optimization in React

  1. shouldComponentUpdate

    This layer of code logic can be described as a simple shallow comparison state. In general, it is not recommended to complete the comparison state, because the component update trigger may be more frequent, so the performance cost of complete comparison is high, and the loss may not be worth the gain

  2. PureComponent

    For shallow comparisons, use PureComponent, which also implements shallow comparison state. For simplicity, think of PureComponent as a simplified version of shouldComponentUpdate

  3. Lazy + Suspense for code splitting and Lazy loading

  4. Use the Production version of react. Js

  5. Use keys to help React recognize minimal changes to all the child components in the list

4. React setState is synchronous or asynchronous

It could be synchronous or asynchronous. Asynchronous only in React composite events and hook functions, synchronous in native DOM and timer

5. React Lifecycle?

It is divided into the old version and the new version of two life cycles, no matter which one, must go through three stages, the initialization stage, update stage, uninstall stage

The old version life cycle

1. In the initialization phase, the execution sequence is as follows:

  1. constructor

    In the past, you could initialize state, bind the function this, and initialize ref

  2. ComponentWillMount (new version deprecated)

  3. render

    Returns the virtual DOM object to render

  4. componentDidMount

    Send requests, start timers, bind events, and so on

The update stage is divided into three kinds of updates, and the execution sequence is as follows:

2. Parent component updates cause child component updates (go complete)

  1. ComponentWillReceiveProps (new abandoned)

    Use this hook function if the child component’s state is determined by props passed by the parent component

  2. shouldComponentUpdate

    It is used for performance optimization, because it can determine if the component needs to be updated, just return a Boolean.

  3. ComponentWillUpdate (new version deprecated)

  4. render

  5. Returns the virtual DOM object to render

  6. componentDidUpdate

    Some things you can do with each update

SetState update componentWillReceiveProps (less)

ForceUpdate update (less componentWillReceiveProps, shouldComponentUpdate)

3. Uninstall stage, execution sequence:

  1. componentWillUnmount

    Can bind event, clear the timer, cancellation, not send successful ajax requests and so on, unbundling is unbundling native dom events, synthetic events don’t need unbundling, unloading method can use ReactDOM. UnmountComponentAtNode ()

New edition life cycle

  1. In the initialization phase, the order of execution:

    1. constructor

    2. getDerivedStateFromProps

      State can be updated before rendering, and the three hook functions that were deprecated in the previous version of the lifecycle are replaced

    3. render

    4. componentDidMount

  2. The update phase is divided into 3 updates, just like the old version

    New hook added after Render componentDidUpdate:

    getSnapshotBeforeUpdate

    You can manipulate the DOM in advance and update it afterwards (rarely used in practice)

  3. Uninstall phase, same as the old version

6. Diff algorithm in React

  1. Tree diff is a method of dividing a tree structure into different levels, comparing only the elements of the same level

  2. Component diff, if the component is of the same type, is compared to the tree diff. If the component is not of the same type, the original component is marked as dirty, replacing all child nodes of the entire component. ShouldComponentUpdate is also used to determine if a component needs to be updated, which is an optimization tool

  3. Element Diif adds a unique key to help React recognize minimal changes to all subcomponents in a list

7. Where do React send requests? Why is that?

Send requests are typically sent in componentDidMount for three reasons:

  1. Sending a request before Render may be called multiple times, not necessary.

  2. The DOM may be manipulated after the request is sent and may not be retrieved before render

  3. Rendering is faster because it is performed after the page has been rendered

8. Tell me about HOC

Hoc is also commonly referred to as a high-order component. In my opinion, the definition of high-order component is essentially a function, which can accept a component as a parameter and return value is a new component. The old component is wrapped in the new component and its function is to reuse code and logic.

How do you react

  1. When JSX does expression judgment, it needs to be cast to Boolean strongly

  2. Try not to use setState in componentWillReviceProps. If you must use setState, then you need to determine the end condition, otherwise infinite rerender will occur and the page will crash

  3. When adding a ref to a component, try not to use an anonymous function, because when the component is updated, the anonymous function will be treated as a new attribute. Therefore, when using an anonymous function to make a ref, sometimes the attribute after the ref is assigned will be null

  4. When traversing a child node, do not pass in index as the component’s key; instead, use a unique identifying ID as the key

10. What’s the downside of Redux

When a component’s data is updated, even if the parent component doesn’t need it, the parent component will still re-render, which may be effective, or need to write shouldComponentUpdate for judgment

11. How to understand virtual DOM? Why does the virtual DOM improve performance

Virtual DOM is equivalent to adding a cache between JS and real DOM. Dom DIff algorithm is used to avoid unnecessary DOM operations, thus improving performance. Use js object structure to generate dom structure tree, and then generate a DOM structure tree in the update, the old and new DOM structure tree is compared, and finally the difference part is replaced and applied to the DOM

12. Division of the React component Business component Technical component

Components are usually divided into UI components and container components based on their responsibilities

  1. The UI component is responsible for rendering the UI
  2. The container component is responsible for managing data and logic

The two are connected via the Connect higher-order component provided by React-Redux

13. What is the difference between createElement and cloneElement?

The createElement function is used by JSX to create a React Element after compilation, while the cloneElement is used to copy an Element and pass in new Props

14. What does the second argument passed to the setState function do?

This function is called when the setState call is complete and the component starts to re-render. We can use this function to listen for the rendering to complete, similar to $nextTick in vue

What is the difference between renderProps and higher-order components?

RenderProps is a simple technique to share code between React components using functions with a value of function. Hoc is essentially a function that accepts a component as a parameter and returns a new component with the old component inside, realizing the reuse of code and logic. I personally feel that renderProps are great for read-only operations, while higher-order components tend to be more complex operations

16. Introduce Hook?

Hook is a technology introduced by React16.8. Essentially, Hook allows us to useState and other react features when using stateless function components. Common hooks include useState, useEffect and custom Hook. UseState is used to define the state. It provides a data method for the state and updating the state. The initial value of the state is the parameter passed by useState. If you don’t pass the second argument, equivalent to componentDidMount and componentDidUpdate, if you pass the second argument to an empty array, equivalent to componentDidMount, if you pass a specified state, A function is executed when the state value changes. If it returns a function internally, it equals componentDidUnmount internally

17. What build component methods are available in React?

React is divided into function components and class components. Function components borrow the idea of stateless components, that is, they can’t use state and lifecycle hooks, and they don’t have the problem of this. The advantage of function components is that they are easier to understand and do not perform any logic unrelated to the UI. You can use bind to redirect this from its constructor, or use the arrow function to fix this. The arrow function is an experimental syntax that has been released

18. Why is it best not to use index for list rendering keys? (See Diff algorithm)

19. What are controlled components and uncontrolled components?

Controlled components collect data through state+onChange events, which is equivalent to manually realizing V-Model in VUE. Uncontrolled components obtain DOM through REF technology and operate native API to obtain data. It is generally recommended to use controlled components when collecting form data

20. What is Portal in React?

Portal is a technique for rendering child nodes to DOM nodes other than their parents. The Modal component in ANTD is implemented using portal technology. The advantage is that the parent component does not re-create the DOM node corresponding to Modal when updating

21. Error boundaries

An error boundary is a React component that catches and prints javascript errors that occur anywhere in the child component tree, rendering alternate UI instead of any broken child tree. However, the error boundary does not catch event handling, asynchronous code, server rendering, or errors thrown by itself. Inside the error boundary are two hook functions (getDerivedStateFromError and componentDidCatch) that determine whether there is an error and upload an error log

7. Webpack interview questions (author is updating…)

8. Vue3 Interview questions (the author is updating…)

9. Typescript Interview questions (author is updating…)