1. Are updates in Vue asynchronous or synchronous?

The data is updated synchronously, the view is updated asynchronously, because if the view is updated synchronously, it will cause multiple renders to waste unnecessary performance. There is no need for it. The Vue is internally de-duplicated (re-updated values) and buffered (only updated last time).

2. What is the principle of nextTick in Vue?

Because update in Vue is asynchronous, sometimes the outside world may want to get the latest DOM element for operation after updating data. In order to achieve a unified effect for users, Vue uses nextTick internally and also allows users to use nextTick. In Vue2, nextTick is compatible. Resolve ().then(), or mutationObserve if it is not supported. If not, use SetimMediate, and then setTimeout. In Vue3 nextTick abandons compatibility and uses promise.resolve ().then() directly. NextTick is also equipped with an anti-shake function to prevent users from calling nextTick multiple times.

3. What is the principle of extend in Vue?

An object is passed in and a class named VueComponent is returned. This class inherits from Vue and can own all the methods on the Vue prototype. The configuration items passed in will match Vue. Vue.component() is used to register the child components. Extend is also called internally to convert the component configuration object into a class that extends from Vue

4. What is the life cycle principle in Vue?

With the strategy mode, all hook functions are put into an array as strings, and then external hooks are overwritten as functions when merged. Manage hook functions on a first-in, first-out basis. When external hooks are called, callHooks are triggered. Internal hooks are called in sequence, and this inside the hook function is changed to an instance of Vue.

5. What is the principle of watch in Vue?

When the key value changes, the handler function corresponding to the key will be called. In fact, the principle of writing in the watch object is the same as that of manually calling vm. watch. The same principle applies to all the watch object handler functions that are converted to vM. watch. In fact, the key(expression) in Watch will finally be evaluated in VM. Then, when the key value changes, watch will be notified to update. After the update is completed, the user’s handler callback will be called to pass in the new value and the old value.

6. What does computed attributes work in Vue?

It is essentially a Watcher, but it has a caching function. It is not triggered by default, it is triggered when a value is evaluated on the page. Every key in computed is defined on the VM. The corresponding value is actually get or GET /set in Object.defineProperty, which is reexecuted when the dependent value changes. If the value of the dependency has not changed, it will not be re-executed, it will return the last value (cache). The key in the calculated property does not collect the render Watcher, only the calculated Watcher. The values that depend on the calculated property all have a Dep, and we should let those DEPs collect the render Watcher. When the value of the dependency changes, the rendering Watcher is notified to update it. The internal cache is controlled by a dirty[‘d ɔ rti] variable as a switch.

7. What is the principle of mixin in Vue?

Vue source code added a static attribute options on Vue, default is an empty object, when we go to call mixin function for mixing, 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 uses mixin to create a befortCreated hook for all components with 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 differentiation 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 pointer to compare. Note: The initial mount does not compare the diff algorithm because the diff algorithm relies on the old and new virtual DOM, and the first mount only generates the virtual DOM once. The virtual DOM is generated during the update. At this time, the old and new virtual DOM will be compared and updated differently. If the tags are the same and the text is different, the new text will be used to replace the old one. If the tags are the same and the text is different, the new text will be used to replace the old one. 4-1, if you have any children, the old node new node has no children, directly to empty the old node children 4-2, if the new node has children, the old node has no children, directly to iterate over the new node, in turn, add 4-3, if all have children, internal will adopt the way of double pointer comparison, contrast head first, if don't, are compared, and the tail end, If the tails are the same, it compares the old tail with the new tail, if not, it compares the old tail with the new head. Note: these comparisons will judge whether the tags are consistent first and then whether the keys are the same. The advantage of judging keys is to reuse older nodes as much as possible. 5, out-of-order comparison: old node: A=>B=>C=>D New node: B=>D=>A=>C=>E Create A mapping table const obj= {A:0,B:1,C:2,D:3} see if the new node exists in the mapping table. First: the old node: A = = > B > C = > D new nodes: B = > D = > A = > C = > E compare B: found, the results are as follows B = > A = > null = > C = > 2 D. Second time: Old node: B=>A=> NULL =>C=>D New node: B=>D=>A=>C=>E Comparison D exists. The result is as follows: B=>D=>A=> NULL =>C=> NULL 3 Third time: Old node: B => D => A => NULL => C => NULL New node: B => D => A => C => E A exists. The result is as follows: B => D => A => NULL => NULL => C => NULL 4. Fourth time: Old node: B => D => A => NULL => NULL => C => NULL New node: B => D => A => C => E Compares C. The result is as follows: B => D => A => C => NULL => NULL => NULL => NULL 5. Fifth old node: B => D => A => C => NULL => NULL => NULL => NEW node: B => D => A => C => E => E => A => C => E => NULL => NULL The above null is only used as a placeholder in the mapping table OBjCopy the code

10. Why must data be a function in Vue?

As a result of javeScript, 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 their own data maintenance, without causing confusion. Nwe 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?

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

12. What is the typical lifecycle for sending requests?

Generally I personally prefer to send requests in Mounted with a few advantages: 1. Does not block page rendering speed 2. / / Mounted returns A.B.C. / / returns A.B.C. / / mounted returns A.B.C. / / Mounted returns A.B.C. / / Mounted returns A.B.C. / / Mounted returns A.B.C. General may return the state A.B.C | | [] some people like to send the request in the created, may consider is a server side rendering it or reduce the loading of the page load time, the service side rendering not mounted the hook function

13. Describe the Vue lifecycle and what you can do in each lifecycle.

Vue has a total of 11 life cycles, BrfortCreate 2.created 1. send request 6 3.beforeMount 4.mounted We do these things 1. Send request 2 Echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo Get update data 3, uninstall stage 7. BeforeDestroy Normally what we do here 1, remove remaining timers 2, remove event listening 2.1 As long as the event is bound by VUE, Destoryed; keep-alive; activated; destoryed ErrorCaptured is one of the first 8 hooks that we use. The hooks activated and deactivated are keep-alive. ErrorCaptured is called when you catch an error in a child component. BrfortCreate: 1. The parent relationship is confirmed ($parent/child already exists) 2. 3. Initialize custom events such as $ON /$emit·/$once/$OFF 4 Initialize slots ($slots). Initialize _c /$createElement (both internally call createElement to create a virtual node). $listeners define $attrs/$Listeners as responsive attributes 6. Initialize some variables on the instance, such as isMounted, isDestriyed, Watcher, etc. Created: 1 calls the beforeCreate hook function for new applications. Initialize inject, inject data, source code inside 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, business data source is not clear, their encapsulation component may be used, can achieve parent-grandson communication, This is not a reactive 2. Initialize props, initialize methods, initialize data, initialize computed, and initialize watch in sequence 3. At this time, data is divided into two types, one is an object and the other is an array. The object will be looped internally, and each attribute in the object will call defineEeactive function to define a response type. The defineReactive function is defined internally with Object. DefieProperty. If the values in the Object are still aligned, the response is defined recursively. They are push, POP, Shift, unshift, splice, sort, reverse. Because they all affect the array, these 7 methods will be overwritten internally. When the user calls these methods, it will actually call the array itself, but will notify Watcher of the update. Moreover, if the user adds data to the array using push, unshift, or splice, The internal gets the added data, determines whether it is an object or not, and if it is an object, defines it again as a response. All received attributes have an __ob__ attribute 4. Initialize provide, which is called if the value of provide is a function with the internal this pointing to the current component instance 5. Call the created hook function beforeMount: See if render is provided. If not, compileToFunction will be called to compileToFunction. There are three things compileToFunction does. Attributes are what), internal will use the re different to match the content of the tag, a bit of the match is deleted, finally match, template is also deleted, return this AST tree 1.2 ast syntax number compiled into strings code, for example: < div id = "# app" > 1 < / div > will be compiled into {tag: 'div', attrs: [{id: 'app'}], 1}, then compile into a string of code, such as: _c('div', {id:"app"},_v(1)); The above code into ƒ anonymous () {with (this) {return \ _c (' div '{id: "app"}, \ _v (1))}} 2. BeforeMount hook (mounted) : 1 Create a render Watcher 2. Do the following three things in Watcher: 2.1 Call pushTarget to save the current Watcher 2.2 Call Render 2.3 Call popTarget to remove 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. Call the mounted hook function beforeUpdate/updated: 1. When the external world updates the data in the data, set will be triggered. Because the dependency has been collected during the previous rendering, we will notify Watcher to update, and then create the virtual node again. This time, the virtual node will be diff compared with the virtual order created before, and then partial update page 2. Call the beforeUpdate hook function 3 before locally updating the page. Call the updated hook function beforeDestory/ Destroyed: 1 after local page updates. When the component is unloaded, it clears the component-bound events, removes itself from $childeren in the current parent component, removes $parent from the current component, and clears watcher 2. Call beforeDestory hook function before component is uninstalled. 3. Call Destroyed hook function after component is uninstalledCopy the code

14. What is the process that the parent component’s life cycle executes?

For initial mounting: 1. Call the beforeCreate function 2 of the parent component. Call the parent component's created function 3. Call the parent component's beforeMount function 4. Call the beforeCreate function of the subcomponent 5. Call the Created function of the subcomponent 6. Call beforeMount function of child component 7. Call Mounted function of child component 8. / / mounted when the parent component is called: 1. See if the updated data is in the child or the parent. If it is in the parent, call beforeUpdate and updated functions in the parent. If it is in the child, call only beforeUpdate and updated functions in the child. This result is due to optimization by diff algorithm 2. If the updated array is in the parent component and the data is passed to the child component, Then the update flow looks like this 2.1 Triggers the beforeUpdate function of the parent component 2.2 Triggers the beforeUpdate function of the child component 2.3 Triggers the updated function of the child component 2.4 Triggers the updated function of the parent component when unloaded: If the parent component is uninstalled, the process is as follows: 3.1 Trigger beforeDestroy of the parent component 3.2 Trigger beforeDestroy of the children 3.3 Trigger DeStoryed of the children 3.4 Trigger Destroyed of the parent componentCopy the code

15. The difference between Computed and Watch

Computed: indicates a computed attribute, depends on other attribute values, and has a cache. Only if the attribute values it depends on change, the computed value will be recalculated to obtain a new value next time. Watch: It is similar to the listening callback of some data. Whenever the listening data changes, the callback will be executed for subsequent operations. When we need to do numerical calculations and rely on other data, we should use computed, because we can take advantage of its caching and avoid recalculating every time we get a value. When we need to do asynchronous or expensive things when the data changes, we should use Watch, Using the Watch option allows us to perform asynchronous operations (accessing an API), limit how often we can perform that operation, and set intermediate states before we get the final result, which cannot be done with computed properties.

Add a property to the object/assign a value to array length, will the page update?

Vue can't detect the above changes due to object.defineProperty. Fix: 1.Vue. 4. You can reassign to the wholeCopy the code

17. Principle of V-Module

The V-Module is used for two-way data binding: templates are compiled into the following 1 when compiled. If you use v-Module on text and Textarea elements, v-Module is the syntactic sugar 2 for the value attribute and input event. If you use v-Module on the checkbox and radio elements, v-Module is the syntactic sugar 3 for the Checked attribute and change event. If you use v-Module on the SELECT element, v-Module is the syntactic sugar 4 for the value attribute and change event. If you use v-Module on a component, v-Module is the syntactic sugar for the value attribute and input eventCopy the code

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

2. V-show is the display property that controls CSS properties to show/hide applicable scenes: V-if is suitable for scenarios where conditions rarely change at runtime and do not need to be switched frequently, and V-show is suitable for scenarios where conditions are switched very frequentlyCopy the code

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

V-for has a higher priority because it loops through all the data first, and then checks through V-IF when the loop is complete, affecting performance. Solution: 1. Process the data by calculating the attributes, and then return the data for rendering 2. You can wrap a tempPlate label on the outside and write v-IF on the labelCopy the code

20. What are the communication methods of Vue components

Parent transmission: Directly bind dynamic data to the child components. The child components use the props property to receive and restrain type 1.2 parent transmission: $on/$emit ='fn'; $on/$emit ='fn'; $on/$emit ='fn'; $on/$emit ='fn'; $on/$emit ='fn'; $on/$emit ='fn'; $parent/$chlidren implements a set of custom events. Parent-child communication can also be implemented 3.1 $parent can obtain instances of the parent component 3.2 $chlidren can obtain all child component instances on the current component 4. Ref implements parent-child communication 4.1 Use ref to obtain DOM elements on ordinary elements 4.2 Use ref to obtain component instances on components EventBus uses $ON /$EMIT to communicate with all components through a common VUE. $ON /$EMIT Business logic data is not normally passed in this way. You can mount some common functions on the Vue prototype, such as: $listeners are aware of the undeclared properties of the parent scope of $attrs.$listeners are aware of the undeclared properties of the parent scope of $attrs Class and style are not included in the process, and native modiators are all v-on events that are not in the parent scope. Inject data into sub-components. 7.2 Common service Data is not recommended because the data source is not clear. 7.3 This method applies to encapsulated components because the data source is clearly knownCopy the code

21. The advantages of virtual DOM

1. No need to manually operate DOM 2. Can use diFF algorithm for optimization, local update 3. Cross-platform, since 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 (SSR).Copy the code

22. Principle of responsive data in Vue

There are four main steps to implement: 1. Implement a listener (Observer) to iterate over the data, including the attributes of the sub-attributes of the Object, such as Object.definePreoperty() to add setters and getters to the attributes. So, if you assign a value to this object, it triggers the setter, and you 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, and bind the corresponding node of each instruction to update data, add subscribers to listen to data, a bit of data change, receive notification, call update function for data update 3. Implement a subscriber (Watcher) : The Watcher is the bridge between the Observer and Compile. Its main task is to subscribe to information about the change of attribute value in the Observer. When receiving information about the change of attribute value, it triggers the corresponding update function 4 in the parser Compile. Implement a subscriber (Dep): The subscriber uses a published-subscribe design pattern to collect subscriber Watcher and manage listener Observer and subscriber Watcher uniformlyCopy the code

23. Principles of template compilation in Vue

1. The template is compiled into an AST syntax tree (the AST is used to describe syntactic information, such as tags and attributes), and the internal re is used to continuously match the content in the tags. When the matches are complete, the template is deleted. <div id='#app'>1</div> will first convert to {tag:'div',attrs:[{id:'app'}],1}, and then compile to string code. For example :_c('div',{id:'app'},_V(1)), this code is the string 3. ƒ anonymous(){with(this){return_c('div',{'id':"app"},_v(1))}} 4 Of course, some instructions/events are handled at compile time.Copy the code

24. What design patterns are used in Vue

1. Publish and subscribe ($ON /$EMIT) 2. Singleton (only one Vue for the whole program) 3. Policy pattern (the lifecycle uses policy pattern to call different callbacks based on different names to solve the if/else problem) 4. The observer pattern (watcher/dep) 5. The proxy pattern: to a certain Object to provide a proxy Object, and the proxy Object to control of the original Object reference, for example: _data while forming, Object. DefineProperty 6. Mediator pattern: Allows components of different parts to communicate by providing a unified interface, such as VUEXCopy the code

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. 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 it is a function, the plugin will call the install method provided by the object and pass the parameters. Call this function and pass in the argument. The return value of use points to Vue without modifying this

Vue. Set principle

Vue. Set (target,key,value) {Vue. Set (target,key,value); If the target you set is an array and the key you pass is an index, the following is done internally. Because splice has been overwritten 1.3 returns value 2. If the target is an object, and the key is present, not new, the following is done internally: 2.1 Modify value (target[key]=value), because if it already exists, it must already be responsive. 2.2 Return value 3. If the target of the setting is an Object and the key is not on the Object itself, the following things are done internally 3.1 calls the defineReactive function, internally defining the data as responsive with Object.defineProperty 3.2 NotifyWatcher to update the page 3.3 Returns valueCopy the code

27. The function and principle of keep-alive

The keep-alive component is used for caching to ensure that the component will not be destroyed. It is an abstract component (it does not render a DOM element itself and does not appear in the parent component chain). The component can define three attributes: 1. Exclude ==> Identifies the components that can be cached. 3. Max ==> Defines the maximum number of components that can be cached. If the number exceeds the threshold, the first cached component will be eliminated and the current cached component will be added. The full name of LRU algorithm is Least Recently Use, which is widely used in cache mechanism. When the space used by the cache reaches the upper limit, it is necessary to cull some of the existing data to maintain the cache availability, and the selection of cull data is done through the LRU algorithm. Principle: 1. Get the keep-Alive wrapped first child component object and its component name 2. Conditional matching is performed based on the set blacklist and whitelist (if any). If no, return component instance 3. Generate a cache key based on the component ID and tag, and check the cache object to see if the component instance has been cached. If so, fetch the cache value and update the key position in this.keys 4. The component instance is stored in the cache object defined in itself, and the key value is saved. Then check whether the number of instances in the cache exceeds the Max value of 5. Set the keep-alive property of the component instance to true to render and execute the wrapped component's hook function: 1. Activated: used when the keep-alive component is activated. Determine the value based on the keep-alive attribute value of the component instanceCopy the code

28. Principles of modifiers in Vue

. Such as: 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 achieve purpose 2. For example. Stop will actually call $event.stopPropagation() and.prevent will actually call $even.preventdefault () 3. Wrap the above functions ($event.stopPropagation()$even.preventdefault ()/$even.preventdefault ()) with a function and return the function. 4. When the real DOM is generated, events are bound to the DOM and functions are addedCopy the code

29. Principles of V-IF and V-FOR

V-if principle: 1. String code that will be processed into ternary expressions during compilation, for example: flag? When render is called, create code block, execute function, and execute JS code V-for principle: 1 This is processed into string code at compile time, such as _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 3 is executed. If we loop through an object and the object has an iterator interface, we use a while loop internally to iterate over the objectCopy the code

30. The implementation principle of slots

Slot is divided into ordinary slot, named slot, scope slot function: slot as a placeholder, according to the conditions to render the corresponding label structure, and can achieve father-son communication principle: 1. Normal slots and named slots are used to render the parent component first, then replace the content in the child component after rendering. When the template is compiled, compile the corresponding string code, and then find the corresponding relationship of slots, and then replace 2. Scope slotCopy the code

31. Advantages of functional components

1. Stateless, no data 2. No life cycle 3. High performanceCopy the code

32, forceUpdate principle

How it works: Manually tell Watcher to do itCopy the code

33. What about Vuex?

Vuex can centrally store and manage the state of all the application components, and can communicate with any component, internally realizing the core concepts of vUe-based responsive system: 1. State module: Drives the data of view applications, which are all responsive data. 2. The Action commits mutation, rather than updating the status directly, and can contain arbitrary asynchronous operations such as sending a request. The mutation module: Vuex and DevTools cannot be monitored if the status is changed. This is a dangerous operation. Generally, we can turn on strict in store to let vuex store enter strict mode. Any mutation handler that accidentally changes the Vuex state will throw an error. The store can be divided into multiple modules, each of which has its own state, mutation, action, getter, and even nested submodules. On the page we can trigger the actions module flow with the function (mapAction)/$dispatch, where we can send request 2. In the Actions module, we can trigger the flow of the Mutations module through commoit, and pass in some data to mutation 3. The module in mutation can get these data and modify the status 4. Once the state changes, the view of the corresponding component is updated. The auxiliary function 1.1mapState, which can be used in component computed by... MapState ([' XXX ']) to map data 1.2mapActions MapActions ([' XXX ']) map action function 1.3mapMutations MapMutations ([' XXX ']) maps the mutation function 1.4mapGetters, which can be computed in the component by... MapGetters ([' XXX ']) to map attributes (2) calculation replaceState role: replace the store root state 3. RegisterModule role: to dynamically register a module 4. CreateNamespacedHelpers role: Plugins in Vuex can return the corresponding helper function (very common) based on the namespace: Vuex's store accepts the plugins option, which is an array that accepts a function as a parameter in the array and either listens to mytation(for external data persistence, logging, or debugging) or commits mutation. The install method incorporates the beforeCrecate hook via vue. mixin, internally giving each component a $store option with the value store instance 2.Store class 1. Recursive cyclic formatting module, mainly for recording parent-child relationship and module registration 2. Recursive cyclic installation module, mainly for the state of the child module to the corresponding parent module, but also to handle namespace path splicing 3. Define the key in the getter module into a container via object.defineProperty. 4. New Vue Define the state and getter of the module in $State and computed 5.Vue of the data Object, respectively. If the 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.$sta te 3. $$store. State [stateName]; $$store. State [stateName]; Expand this objectCopy the code