* How to answer interview questions
1. First, a clear definition of this point, or a characteristic;
2. Specific application scenarios;
3, say their own views, views;
4, you can talk about similar features, or similar framework, better scheme.
The text starts here ~~~
NO1. Often tested – Basic point
1. How is MVVM architecture better than MVC?
The MVC pattern is the basis of the MVVM pattern, and MVC and MVVM are not really that different. It’s all a design idea. Basically, the Controller in MVC morphed into the viewModel in MVVM.
MVVM mainly solves the problem that a large number of DOM operations in MVC reduce page rendering performance, slow loading speed and affect user experience. And when the Model changes frequently, developers need to actively update the View.
MVC, all communication is one-way.
-
View sends instructions to Controller;
-
After the Controller completes the business logic, it requires the Model to change its state;
3) The Model sends the new data to the View and the user gets feedback.
Simplification of MVVM mapping relationships.
1) Communication between all parts is bidirectional;
2) Bidirectional binding: Changes to the View are automatically reflected in the ViewModel and vice versa.
Vue core features
Data driven (MVVM), componentized, instruction system.
The difference between a library and a framework is that a library is called by its users, whereas a framework is called by others.
2. What are the advantages and disadvantages of SPA single page?
* Key answers:
SPA (Single-Page Application) loads the corresponding HTML, JavaScript, and CSS only when the Web page is initialized. Once the page is loaded, SPA will not reload or jump the page because of the user’s operation. Instead, routing mechanisms are used to transform HTML content, interact with the user and avoid page reloading.
Advantages:
1) Good user experience, fast, content change does not need to reload the whole page, avoid unnecessary jump and repeated rendering;
2) SPA has less pressure on the server;
3) The responsibilities of the front and back ends are separated, and the architecture is clear. The front end carries out interactive logic, while the back end is responsible for data processing;
Disadvantages:
1) Slow loading of the first screen (the first time) : In order to achieve single-page Web application functions and display effects, JavaScript and CSS need to be loaded uniformly when loading the page, and some pages need to be loaded as required;
2) Bad for SEO: Because all content is displayed dynamically on a page, it has a natural disadvantage in SEO.
3. Vue (important)
-
Some modifiers are processed by components at compile time (different code is generated for different modifiers)
-
There are some modifiers you have to deal with when you actually run it
-
Once,passive, and capture must perform special handling when binding events. [create,update,destroy] The corresponding property hooks are called to create the corresponding function.
There are five types of modifiers in VUE:
1) Form modifiers
-
The lazy change event is followed by information synchronization.
-
Trim Automatically filters the first space character entered by the user, but the middle space is not filtered.
-
Number automatically converts the user’s input value to a numeric type.
2) Event modifier
-
Stop prevents event bubblings, which is equivalent to calling the Event. stopPropagation method
-
Prevent prevents the default behavior of the event, which is equivalent to calling the event.preventDefault method
-
Self fires the handler only if event.target is the current element itself
-
Once can only trigger an event once
-
Capture is used for event capture
-
Passive tells the browser that you do not want to block the event’s default behavior
-
Native binding native events
3) Mouse button modifier
-
Left click
-
Right click
-
Middle Middle click
4) Key value modifiers
- Common keys (Enter, TAB, Delete, Space, ESC, Up…)
- System Modifier keys (CTRL, Alt, Meta, Shift…)
5) v – bind modifier
-
Async can perform a bidirectional binding to props
-
Prop sets custom tag properties to avoid exposing data and contaminating HTML structures
-
Camel changes naming to camel nomenclature, such as converting the view-box attribute name to viewBox
Listening for an event on a normal HTML tag and then adding the.native modifier won’t work.
<div id="app"> <a href="#" v-on:click.native="clickFun">click me</a> </div>
Copy the code
Listen for an event on the root element of a component, after which adding the.native modifier takes effect.
<div id="app"> <my-component v-on:click.native="clickFun"></my-component> </div>
Copy the code
4, Vue. Sync modifier function, usage and implementation principle
-
Sync has been removed from vue3, and v-model-like syntactic sugar can be parsed to the corresponding result
-
: XXX. Sync = “ABC” : XXX = “ABC” : update: XXX = “v = > ABC = v” can be achieved. The sync
-
The default values passed by v-model are called value and input unless the user overwrites them
5. How to understand custom instructions
-
1. When generating the AST syntax tree, add the cache property ‘{directive:’ V-for ‘,name:for}’ to the current element.
-
2. Generate instruction code by genDirectives
-
3. Extract the hook of the instruction to CBS before patch, and invoke the corresponding hook during patch
-
Inserted,bind,unbind, componentUpdate 4. While the CBS hook is executed, call the corresponding instruction’s defined methods (CREATE /update/destroy) and the user-defined instruction’s hook function (Inserted,bind, Unbind, componentUpdate).
directives: [{ name: “model”, rawName: “v-model”, value: (xxx), expression: “xxx” }]
6. What happens to new Vue()?
* Key answers:
1) Conclusion: New Vue() creates an instance of Vue, which internally performs the initialization of the root instance.
2) Include the following operations:
-
Option to merge
-
Children, children, children, refs, slots, slots, createElement, etc
-
Custom event handling
-
Data responsive processing
-
Lifecycle Hook calls (Beforecreate Created)
-
Possible mount
3) Summary: New Vue() creates the root instance and prepares the data and methods. This process is recursively applied to its child components for future mount operations, resulting in a tightly related tree of component instances.
Source address: SRC/core/instance/init. Js
7. What does vue.use do? How does it work?
* Key answers:
Vue. use is used to work with plug-ins, where we can extend global components, directives, prototype methods, and so on.
1, check whether the plug-in is registered, if registered, then directly jump out;
2, process the input parameter, collect the parameters after the first parameter, and insert this context in the header;
3, execute the registration method, call the defined install method, pass in the processing parameters, if there is no install method and the plug-in itself is function, directly register;
* Supplementary answers:
-
Plugins that use VUE are passed through vue.use (plugin), and the user passes in the VueRouter when using this plugin to solve the version-dependent problem.
-
The VueRouter library relies on vUE. My vue version is 2.6, separating the plug-in from vue’s strong dependency.
-
Plug-ins cannot be loaded repeatedly
The first argument to the install method is the vue constructor, and the other arguments are all the arguments in vue. Set except the first argument. Code: the args. The unshift (this)
-
Typeof plugin.install === ‘function’
-
The plug-in itself is a function and lets the function execute directly. Plugin. Apply (null, args)
-
Cache plug-in. Code: installedPlugins. Push (plugins)
SRC /core/global-api/use.js
8. Please explain your understanding of Vue2.X responsive data.
* Key answers:
Depending on the data type, how arrays and object types are hijacked when values change.
- DefineReactive method is used internally to collect data dependency by using Object.defineProperty() to monitor get of data attribute, and then distribute data update through set.
** Important: ** Multi-level objects are hijacked by recursion. The bug is that you build recursively, and non-existent properties cannot be monitored.
- Arrays are implemented by overriding array methods. Extend its seven change methods by listening to them for dependency collection and distribution of updates; ( push/pop/shift/unshift/splice/reverse/sort )
* Optimization scheme:
-
In Vue2, the nesting of hierarchical data should not be too deep.
-
Freeze if you don’t need responsive data, don’t put it in data.
-
We try to cache used variables;
In vue3, we use proxy to realize responsive data. For example, we use proxy to realize responsive data.
Extension:
MVVM as a data binding entry, integration Observer, Compile and Watcher, through the Observer to monitor their model data changes, can use Complie to parse and Compile template instructions, Finally, Watcher is used to bridge the communication bridge between Observer and Compile to achieve data change -> view update; View Interactive Changes (INPUT)-> Bidirectional binding effect of data model changes.
* Supplementary answers:
Responsive process:
DefineReactive Defines data as reactive;
2. Add a DEP to the property to collect the corresponding watcher;
3. Update the data as it changes
Dep.depend () // get Value: Collects dependencies
Dep.notify () // When set is set: notifies view updates
1) If the object hierarchy is too deep, the performance will be poor. 2) Do not place content in data that does not require response data. 3) Object.freeze () can freeze data.
Source address: SRC/core/observer/index, js, 158
9, Vue3. X responsive data principle
* Key answers:
Vue3 uses proxy directly to intercept objects (listening to the changes of objects and arrays), without rewriting get and set methods, high performance, no need for direct recursion. DefineProperty is not used for arrays because arrays may be long but the user does not manipulate the index to change the data.
Proxy only proxies the first layer of an object, so how does Vue3 handle this?
Check if reflect. get is Object, and reactive is used to proxy it.
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.
How does Vue detect array changes?
* Key answers:
Instead of intercepting each entry of an array for performance reasons, we chose to override the array method instead. When the array calls the 7 methods, ob.dep.notify() is called to issue the notification Watcher update;
* rewrite array methods: push/pop/shift/unshift/splice/reverse/sort (seven mutation method can change the way of the original array)
* Supplementary answers:
Vue2 didn’t use defineProperty to detect our array (poor performance), Vue2 uses the method of rewriting the array to achieve (7 variations can change the original array method) through the prototype chain + function hijacking (the defect is that the index change and the array length change can not be detected) the array elements will be observed again.
-
Changing the index and length of an array in Vue is not monitored.
-
The data is also recursively hijacked if it is an object data type.
You need to modify the array through the following 7 mutating methods to trigger the wacther update of the array. Arrays of object data types are also recursively hijacked.
What if you want to change the index to update the data?
This can be done with vue.set () = “the inner core uses the splice method.
// Retrieve the prototype method; Const arrayProto = array. prototype; Export const arrayMethods = object.create (arrayProto); def(arrayMethods, method, function mutator (... Args) {} ob.dep.notify() // Update view when calling method;Copy the code
Source address: SRC/core/observer/array. Js 15
11. How to collect dependencies in Vue? (Observer mode)
How does internal dependency collection work?
-
Each attribute has its own DEP attribute, which stores the watcher it depends on. When the attribute changes, it will inform its corresponding Watcher to update it.
-
The render function is called by default on initialization, and property dependency collection dep.depend() is triggered at some point;
-
The watcher update dep.notify() is triggered when the property is modified;
The purpose of dependency collection is to update the view if the data changes, and how each property collected has a DEP property and each object has a DEP property. Each component creates a render Watcher during the rendering process (there are three types of watcher: render Watcher, calculated property Watcher, and user Watcher). A property may have multiple Watchers, and in turn a watcher may have multiple DEPs.
When the value method is called, if there is a watcher, it will collect the watcher. When the data changes, it will notify the corresponding DEP to trigger the update and call the watcher.update method.
12, How to implement vue.set method?
* Key answers:
We add deP attributes to both the object and the array. When we add non-existing attributes to the object, we trigger the watcher that the object depends on to update it. When we change the array index, we call the splice method of the array itself to update the array.
Important:
-
If the object is responsive, then the object itself will have a DEP attribute. When the new attribute is added, the watcher corresponding to the DEP will be triggered to update.
-
The splice method is called for arrays inside, and the defineReactive method is called and notify manually for objects.
* Supplementary answers:
Vue. Set (Object, key, value)
- If it’s an array, call the overridden splice method (so you can update the view)
Target.splice (key, 1, val)
-
If it’s not reactive you don’t need to define it as a reactive property.
-
If it is an object, define the attribute as reactive defineReactive(ob.value, key, val)
Notifying view updates ob.dep.notify()
Source address: SRC/core/observer/index, js, 202
How does template compilation work in Vue?
* Key answers:
At the heart of the template compilation principle is ast -> generated code.
Converting template to render function (note that we should avoid using template in development, since converting template to render method requires compilation at runtime and has a performance penalty, By default, template processing in vue files is handled by vue-loader, not by runtime compilation.
-
Convert the Template template to the AST syntax tree – parserHTML
-
Static markUp (vue3 template compilation is optimized patchFlag, blockTree, event cache, node cache…)
-
CodeGen Splices render Function string + new Function + with
* Supplementary answers:
Template engine implementation principle is new Function + with to implement.
Vue-template-compiler is used to process the template attribute in vue-loader
vue-loader
// template => ast => codeGen => with+function render } = VueTemplateCompiler.compile(`<div>{{aaa}}</div>`) console.log(ast, With + new Function console.log(new Function(render).tostring())) // With (this){return _c('div',[_s(aaa)])Copy the code
Source code Settings:
Const ast = parse(template.trim(), options) // Parsing code into ast syntax tree if (options.optimize! {optimize(AST, options) // static point markup tree} const code = generate(ast, options) // generate codeCopy the code
SRC /compiler/index.js
14. Comparison between Proxy and Object.defineProperty
* Key answers:
Advantages of Proxy are as follows:
1) Proxy can listen directly on objects instead of properties;
2) Proxy can directly monitor array changes;
3) Proxy has up to 13 interception methods, not limited to apply, ownKeys, deleteProperty, has, etc. Object. DefineProperty does not have;
4) Proxy returns a new Object, we can only manipulate the new Object to achieve the purpose, while Object.defineProperty can only be directly modified by traversing Object attributes;
5) Proxy as a new standard will be subject to continuous performance optimization by browser manufacturers, which is the performance bonus of the legendary new standard;
Object.defineproperty has the following advantages:
It has good compatibility and supports IE9, but Proxy has browser compatibility problems and cannot be smoothed by Polyfill. Therefore, the author of Vue announced that Proxy can be rewritten until the next big version (3.0).
NO2. Constant examination – Life cycle
What are the lifecycle methods of Vue? At what stage is the request initiated and why
* Key answers:
There are 8 stages: before/after creation, before/after loading, before/after updating, and before/after destruction.
1. Before/after creation:
- BeforeCreate stage: the mount element EL and data object data of the VUE instance are both undefined and not initialized.
Note: In the current phase, data and methods on Data, methods, computed, and watch cannot be accessed.
- Created phase: VUE instance data object data is available, el is not.
Note: You can do some initial data fetching, at this stage can not interact with the Dom, if you want to, you can use vm.$nextTick to access the Dom.
2. Before/after loading:
- BeforeMount phase: The $EL and data of the vue instance are initialized, but the previously virtual DOM node is still mounted.
Note: The virtual Dom has been created and is about to start rendering. Data can also be changed at this point without triggering the updated.
- Mounted: The Vue instance is mounted, and data.message is successfully rendered.
Note: In the current stage, the actual Dom is mounted, data is bidirectional bound, Dom nodes can be accessed, and Dom can be manipulated using the $refs attribute.
3. Before/after update:
- BeforeUpdate phase: Called during reactive data updates, which occurs before the virtual DOM is patched and is suitable for accessing the existing DOM before updates, such as manually removing event listeners that have been added.
Note: Data can be changed at this stage without rerendering.
- Updated phase: called after the virtual DOM is re-rendered and patched, the DOM is updated to avoid data manipulation in this hook function and prevent endless loops.
Note: The component Dom has been updated at this stage. It is important to avoid changing the data during this period, as this may result in an infinite loop of updates.
4. Before/after destruction:
- BeforeDestroy stage: called before the instance is destroyed. The instance can still be used. This gets the instance.
Note: The instance is fully usable in the current phase, where we can clean up after work, such as clearing timers.
- Destroyed phase: Called after the instance is destroyed. All event listeners are removed and all subinstances are destroyed.
Note: At this stage the component has been disassembled, the data binding has been removed, listeners have been removed, and subinstances have been destroyed.
* Supplementary answers:
BeforeCreate, Created, beforeMount, mounted is triggered when the page is loaded for the first time.
-
A Created instance has been created because it is the first trigger to make requests for data and resources. (Server rendering supports created methods)
-
The Mounted instance is mounted. DOM operations can be performed on it. (Interface request)
Source address: SRC/core/instance/lifecycle. Js
2. How are lifecycle hooks implemented?
* Key answers:
-
Vue lifecycle hooks are simply callback functions that are called during component instance creation.
-
The hook functions are handled internally, maintaining them as arrays.
* Supplementary answers:
Lifecycle hooks are internally maintained by the VUE as an array (vUE has a mergeOptions method inside) and global lifecycle merges are eventually converted into arrays, which are called by publishe-subscribe hooks when the process is executed.
Source address: SRC/core/util/options. Js 146 core/instance/lifecycle. Js 336
Vue’s parent and child lifecycle hooks are executed in sequence
* Key answers:
BeforeCreate, Created, beforeMount, and Mounted are triggered the first time a page is loaded.
Rendering process:
Mouted is mounted after the parent component. Mouted is mounted after the child components. Mouted is mounted after the parent component
Parent beforeCreate -> Parent created -> parent beforeMount -> child beforeCreate -> child created -> child beforeMount -> Child Mounted -> parent Mounted
Sub-component update process:
Affects the parent component: Parent beforeUpdate-> child beforeUpdate-> Child updated -> Parent updTED
Does not affect parent component: child beforeUpdate -> Child updated
Parent component update process:
Affects child components: Parent beforeUpdate-> child beforeUpdate-> Child updated -> Parent updTED
Does not affect child components: parent beforeUpdate -> Parent updated
Destruction process:
Parent beforeDestroy -> Child beforeDestroy -> Child destroyed -> Parent destroyed
Important: The parent waits for the child to complete before executing its own completed hook.
NO3. Constant test – Component communication
1. Why is data of components in Vue a function?
* Key answers:
Since Vue. Extend will be called internally to pass in the definition of the component, the user’s parameters will be merged to detect the data property. If data is not a function, a warning will be reported, and the data currently defined will be merged into the component.
const Sub = Vue.extend({ data(){ return {a:1} } }) new Sub({props,slot}); new Sub({props,slot});
The component is instantiated each time it is used, and the data function is called to return an object as the data source for the component. In this way, data of multiple components is not affected by each other.
If data is an object, the object is a reference type that affects all instances. So to ensure that data does not conflict between different instances of the component, data must be a function.
SRC /core/util/options 121
2. What are the ways of communication between Vue components?
* Key answers:
Vue component communication refers only to the following three types of communication: parent-child component communication, intergenerational component communication, and sibling component communication. We will introduce each of these communication modes and explain which types of component communication this method can be applied to. 1, Props / $emit is a method for parent/child component communication. This method is the basis of Vue component communication, so I will not give an example.
Parent /parent /parent /children = parent/parent /child = parent/parent /child If used on a child component, the reference refers to the component instance 2) parent/parent /parent /children: accesses the parent/child instance
EventBus (emit/emit /emit /on) is a method that uses an empty Vue instance as the central EventBus (event center) to trigger events and listen for events, thus implementing communication between any components. Includes parent-child, intergenerational, and sibling components.
4, attrs/attrs/attrs/listeners applies to every generation component 1) attrs: contains the parent scope are not prop feature recognition (and gain) by binding (except the class and style). When a component does not declare any prop, it contains all bindings in the parent scope (except class and style), and v−bind=”attrs: contains feature bindings (except class and style) in the parent scope that are not recognized (and retrieved) by prop. When a component does not declare any prop, it contains all bindings in the parent scope (except class and style), and contains feature bindings (except class and style) in the parent scope that are not recognized (and retrieved) by prop by v-bind=”attrs: “. When a component does not declare any prop, all parent-scoped bindings (except class and style) are included, and the internal component can be passed in via v−bind=”attrs”. Often used in conjunction with the inheritAttrs option. 2) Listeners of v−on events in parent scopes (native modifiers are not included) Listeners can notice the process by means of V −on=” Listeners: V-ON event listeners in the parent scope (without the.native modifier). The listeners can be listeners of V-on events in the parent scope (native modifiers are not included) via V-on =”listeners: Internal components can be passed on via V − ON =” Listeners”
5. Provide/inject This function is applicable to provide variables by Provider in ancestor components and inject variables by inject in descendant components. Provide/Inject API mainly solves the communication problem between cross-level components, but its usage scenario is mainly that sub-components obtain the state of the upper level components, and a relationship between active provision and dependency injection is established between cross-level components.
Vuex is a state management mode developed specifically for vue.js applications. At the heart of every Vuex application is the Store. A “store” is basically a container that contains most of the states in your app.
3. What are the benefits and functions of writing the name option in the component?
* Key answers:
-
You can find the corresponding component by name (recursive component)
-
Caching can be implemented with the name attribute (keep-alive)
-
Components can be identified by name (important when communicating across tiers of components)
Benefit 1: you can recycle your own components in your own components.
Benefit 2: after having a name, you can locate the specific component and constantly find a component and send events to this component;
Vue.extend = function () {
if(name) {
Sub.options.componentd[name] = Sub
}
}
Copy the code
SRC /core/vdom/create-element.js 111
4. Where is keep-alive used at ordinary times? The principle is?
* Key answers:
-
What is a cache? Cache the component instance, vm.el on the component instance (caching the instance is caching the DOM element). If the component is cached during the switch, it can simply reuse the vm.el that was rendered last time (caching the instance means caching the DOM element). If the component has a cache when switching, it can simply reuse the vm.el result that was rendered last time.
-
Keep-alive does not do any rendering and internally uses an LRU algorithm to manage the cache (abstract components).
-
$forceUpdate is re-rendered if the contents of a keep-alive component change.
Keep-alive is mainly component cache and adopts LRU algorithm. The most recent unused method.
Two commonly used attributes include/exclude allow components to cache conditionally.
Two life cycles, activated/deactivated, are used to determine whether the component is active.
Abstract: true, // The abstract component props:{include: patternTypes, // What to cache exclude: patternTypes, // What to exclude Max: [String, Number] // Maximum cache Number} if(cache[key]) { Vnode.componentinstance = cache[key]. ComponentInstance remove(keys, } else {cache[key] = vnode // Not cached key. push(key) // Store key if(this.max &&) Keys. length > parseInt(this.max)) {// Delete the earliest cached pruneCacheEntry(cache, keys[0], keys, This._vnode)}} vnode.data.keepAlive = true // The flag is cachedCopy the code
5. Application scenarios and principles of Vue.minxin?
* Key answers:
The function of vue. mixin is to extract the common business logic, similar to the principle of “object inheritance”. When the component is initialized, mergeOptions method will be called to merge, and the strategy mode will be used to merge different attributes. If the mixed data conflicts with the data in its own component, The “proximity rule” applies to the data of the component.
-
The main problem with Vue. Mixin is the common logic, which can be removed by adopting mixins (more commonly, react-high order functions, hooks, compositionApi).
-
Vue3 uses a composite API to make it more convenient.
-
Internal implementation principle is mainly used is mergeOptions to merge data into the global options, each component initialization will be merged options.
* Supplementary answers:
There are many defects in mixins — naming conflicts, dependency issues, data source issues — and mixin data is not shared.
SRC /core/util/options.js
Talk about the understanding of Vue componentization
Componentalization first appeared in webComponent browsers that could implement custom tags with poor compatibility. The benefits of componentization (in order to achieve component-level updates, reasonably planned code, strong reuse, one-way data flow)
Componentization often involves technical attributes, events, slots (which components I encapsulated, how I encapsulated them, how I redeveloped from existing components)
7. Vue component rendering process
Components written (used as tags) -> AST syntax tree, identified by the component to create a virtual node -> components become real nodes -> inserted into the page
-
Register components that are available in the current instance
-
Vue.extend creates a component class Sub from the component object
-
Create a virtual node of a component on which the component adds the lifecycle hook init method
-
Component virtual nodes will contain a componentOptions(Sub, Children…)
-
Component initialization calls the component’s init hook (new Sub ($mount))
-
Generate a virtual node based on the content of the component, create the node, and insert it into the page
8. Vue component update process
What would cause a component to update? 1) The component’s own state changes. 2) The props change also causes the parent component to update and the child component to update.
PropsData = propsData If the responsive data changes the page will be updated
9. Principle of asynchronous components in Vue
For lazy loading of standard images, the process is to render an empty node first, and then after the component is loaded, it needs to force the rendering to reload the component again.
10. Advantages and principles of functional components
This does not have its own data source, it can accept props, simple page rendering can use function components (the normal component is a _init() class, but the function component is a normal function). The functional components are then re-rendered.
11. The way of value transmission between Vue components and the differences between them
How many ways are there to interact? “Many.”
-
Props, EMIT typical parent-child communication
-
What do brothers use to pass values to each other? You can communicate with a common parent, or you can use eventBus
-
Communicating eventBus across components, Vuex can implement Vue.Observable
-
Inject provide The development component library can be used. It is not recommended to use it in other scenarios because the data source is not clear
-
Parentparent ParentChildren Gets instances of parent and child components
-
$refs Parent gets instance of child
-
Attrs Listeners can also communicate all properties and methods passed by the parent component to the child component
*props and emit implementation
-
Props is separated from propsData in componentOptions during virtual node creation. During initialization, propsData is defined on the _props of the component, and then propped to the instance
-
Emit events are defined on component instances by default and are placed on vm.$options._parentListeners when onEMIT is resolved
*parent children
The parent component can be retrieved during component initialization to construct the parent-child relationship
* Inject provide how to realize cross-level communication parent {a:1}- “grandson -” great-grandson – “great-great-grandson -” great-great-grandson
-
The parent component defines the data on vM._provide
-
The child component looks up through vm.$parent and defines the attributes it finds on its own
attrs listeners
-
Get all the events and attributes defined directly on the instance
-
defineReactive(vm, ‘$attrs’, parentData && parentData.attrs)
-
defineReactive(vm, ‘$listeners’, options._parentListeners)
refs
-
You can get the component instance after you add it to it
-
$refs = vnode.componentInstance || vnode.elm;
What problem does $attrs appear to solve, and provide and inject don’t solve the problem it solves?
- V-bind =”attrs”v− ON =”attrs”v−on=”listeners” can directly and quickly send attributes and events down. Layer by layer, can not achieve cross-level transmission
- Provide and inject are mainly cross-level communication. They do not need to be passed around and can be provided in the parent component and directly consumed by the child component
12. How is slot implemented in Vue? When to use it?
1) Build a mapping table for the named slot
2) Normal slots are used to render vNodes in the parent component (only the parent component’s data can be rendered and passed to the son)
3) The scope slot renders the contents of the custom column of the table component of vNode in the subcomponent (you can use the data of the subcomponent to continue rendering).
NO4.常考- Routing
How many hook functions does vue-router have? What is the specific and what is the implementation process?
* Key answers:
The execution flow of the route hook, the hook function types are: global guard, route guard, component guard.
* Complete navigation parsing process
1. Navigation is triggered.
2. Call the beforeRouteLeave guard in the deactivated component;
3. Call the global beforeEach guard;
4. Call the beforeRouteUpdate guard in the reuse component;
5. Invoke the beforeEnter guard in the routing configuration.
6. Parse asynchronous routing components.
7. Call the beforeRouteEnter guard in the activated component;
8. Call the global beforeResolve guard;
9. Navigation is confirmed;
10. Call the global afterEach hook;
11. The DOM updates;
12. Call the callback passed to Next in the beforeRouteEnter guard with the created instance.
2. What are the differences between vue-Router and VUE?
* Key answers:
Vue-router has three routing modes: hash, history, and Abstract.
- Hash mode: hash + hashChange
Features: Hash is in the URL, but is not included in the HTTP request. Hash is used to instruct browser actions. It is useless for server security and does not reload pages. Execute JS code by listening for hash (#) changes to the page.
Core code:
Window. The addEventListener (‘ hashchange ‘, function () {
self.urlChange()
})
- History mode: historyApi + popState
HTML5’s history API uses pushState() to record operation history and listens for popState events to detect state changes.
Because simply refreshing the URL (www.ff.ff/jjkj/fdfd/f… Configure the server side.
Description:
1) Hash: Uses the URL hash value for routing. Support for all browsers, including those that don’t support the HTML5 History Api; 2) History: Rely on the HTML5 History API and server configuration. See the HTML5 History mode; 3) Abstract: All JavaScript runtime environments are supported, such as node.js server. If the browser API is not found, routing automatically forces the mode into this mode.
NO5.常考- Attribute function and contrast
1. Where is nextTick used? The principle is?
* Key answers:
NextTick’s callback is a deferred callback that is executed after the next DOM update cycle ends. Use this method immediately after modifying the data to get the updated DOM. NextTick mainly uses macro and micro tasks. The principle is that asynchronous methods (promise, mutationObserver, setImmediate, setTimeout) are often asked in conjunction with event loops.
-
The nextTick function is batch processing. Multiple calls to the nextTick function will temporarily store the logic in the queue, which will be refreshed synchronously after the execution of the synchronized code. (The nextTick function is asynchronous internally, but the logic is executed synchronously.)
-
SetImmediate Mediate Mediate Mediate Mediate Mediate Mediate Mediate Mediate Mediate Mediate Mediate Mediate Mediate Mediate Mediate Mediate
* Supplementary answers:
Vue updates the data multiple times, eventually making batch updates. The internal invocation of nextTick implements deferred update, and the callback in user-defined nextTick is deferred until the update is complete to retrieve the updated DOM.
SRC /core/util/next-tick.js 42
2. Why does Vue need virtual DOM? How good and bad is the virtual DOM?
* Key answers:
Virtual DOM uses JS objects to describe the real DOM, which is an abstraction of the real DOM. Since the performance of direct DOM operation is low but the operation efficiency of JS layer is high, DOM operations can be converted into object operations, and finally THE DOM can be updated through diff algorithm to compare the differences (reducing the operation on the real DOM). The virtual DOM can also be cross-platform without relying on the real platform environment.
* important:
-
The most core is cross-end, different platforms to achieve different schemes. Internal implementations may not be limited to browser platforms;
-
If developers manipulate the DOM too often, it may waste performance. Virtual DOM you can think of it as adding a layer of caching. We will update the virtual DOM first, before updating it on the page;
-
Because DOM diff compares virtual DOM comparisons before and after the updated page (or real Domdiff performance is poor);
-
Multiple DOM operations will cause the browser to merge;
* Supplementary answers:
The implementation of the virtual DOM is the description of real nodes by ordinary objects containing tags, data, children and other attributes. (Essentially a cache between JS and DOM)
Vue2’s Virtual DOM is based on the open source library SNabbDOM.
VirtualDOM mapping to the real DOM goes through the create, diff, and Patch stages of a VNode.
SRC /core/vdom/vnode: 3
3. The function and working principle of key in Vue, tell me your understanding of it
* Key answers:
For example: v-for=”(item, itemIndex) in tabs” :key=”itemIndex”
Key is mainly used to update virtual DOM efficiently. The principle is that vUE can accurately judge whether two nodes are the same or not through key during patch, thus avoiding frequent updates of different elements, making the whole patch process more efficient, reducing DOM operations and improving performance.
* Supplementary answers:
The key is used to indicate uniqueness and can be reused during diff calculations. Check whether it is the same node (tag, key). Try not to use indexes for keys in dynamic lists (if you use indexes, you will not write keys), which may cause update problems. (If the list is dead, use the index as the key.)
SRC \core\vdom\ patch.js-updatechildren ()
4. Diff principle in Vue
* Key answers:
Vue diff algorithm is horizontal comparison, not considering the case of cross-level comparison. Internally, the method of deep recursion + double pointer is used for comparison.
* important:
-
Diff algorithm is O(N) level, which uses peer comparison and internal depth-first traversal to traverse nodes.
-
The node checks whether it is the same element. If it is the same element, it compares the attributes with the children. If it is not, it directly deletes the old one and replaces it with the new one
-
Vue2 adopts double Pointers to optimize some scenes (diff algorithm can be skipped if the nodes are static).
-
Head, tail, tail, head, head
-
Finally, out-of-order comparison is to create a mapping table according to the old nodes, and use the new ones to find reusable nodes within the reuse (the out-of-order order may be fixed in the middle, but they will all be moved once).
There is also a blockTree concept in VUe3. If it is compiled by template, dymanicChildren will be formed into an array and directly compared with the array, which has better performance. If this method cannot be used, full comparison (V-for) will be used.
Vue3 optimizes mobile nodes by using the longest increasing subsequence to achieve greedy + binary search + O(nlogn) of precursor nodes;
* Supplementary answers:
-
First, check whether the node is the same
-
Compare attributes of the same node and reuse the old node
-
Compare the sons, considering the sons of the old node and the new node
-
Optimization comparison: head, tail, head, tail
-
Comparison lookups are reused
Diff algorithm of Vue2 and Vue3. X:
The core Diff algorithm of Vue2 adopts the algorithm of double-end comparison, which starts from the two ends of the old and new children, finds the reusable node with the help of key value, and then carries out relevant operations.
Vue3. X draws lessons from IVI algorithm and Inferno algorithm, which also uses the idea of dynamic programming to solve the longest recursive subsequence. (The actual implementation can be viewed with Vue3. X source code.)
SRC /core/vdom/patch.js 501
5. Priority of V-IF and V-for
* Key answers:
1. V-for is resolved before V-if
2. If it happens at the same time, each render will execute a loop before judging the condition, so the loop is inevitable anyway, wasting performance
3. To avoid this, create a nested template on the outer layer, do a V-if judgment on this layer, and then do a V-for loop on the inside
4. If the condition is present inside the loop, you can filter out the items that do not need to be displayed in advance by calculating the attributes
Source address: the compiler/codegen/index. Js
if (el.staticRoot && ! el.staticProcessed) { return genStatic(el, state) } else if (el.once && ! el.onceProcessed) { return genOnce(el, state) } else if (el.for && ! El.forprocessed) {v-for return genFor(el, state)} else if (el.if &&! } else if (el.tag === 'template' &&! el.slotTarget && ! state.pre) { return genChildren(el, state) || 'void 0' } else if (el.tag === 'slot') { return genSlot(el, state) }Copy the code
6. Realization principle of V-IF, V-Model and V-for
1) The V-for principle is to concatenate a loop function with a method _L inside
2) V-if is automatically escaped to ternary expressions (v-for and V-if) and does not compile directive. These two things are escaped when generating code
3) V-Model can be used on components (to synchronize component data) (and also on elements) to add instructions
4) V-model is the syntactic sugar of value + input in the component
5) The V-model is somewhat different when placed on a form element and will be interpreted as an instruction (the V-Model will be interpreted as an instruction at compile time). By default, the input event will be concatenated to handle the Chinese input method. The v-model.lazy modifier is also handled when the directive is invoked at runtime (which does different things for different types)
7. V-if vs. V-show
* Key answers:
V-if is true conditional rendering and does not begin rendering until the condition is true for the first time.
V-show renders regardless of initial conditions, and simply switches based on the “display” property of CSS.
Note: V-if is suitable for scenarios that do not require frequent switching conditions; V-show is suitable for scenarios that require very frequent switching of conditions.
8. What are the differences between computed and Watch and the application scenarios?
* Key answers:
-
Computed and Watch are based on Watcher;
-
Computed: Calculates attributes. If there is a cache, the dependent value does not change, and the calculation attribute method will not be re-executed when it is evaluated.
-
Watch: Monitors data changes. Monitors value changes and calls the corresponding callback function when the value changes.
* Supplementary answers:
-
The difference is that computed data can be used for page rendering, but Watch can’t;
-
Computed performs the corresponding callback only when it is evaluated (lazy is true so it does not perform it immediately); watch executes it once by default (to get the old value). Computed uses a dirty attribute to implement a caching mechanism. Multiple values do not change the dirty result if the dependent value does not change, and the old value is obtained.
Application scenario:
1) Use computed data when you need to do numerical calculations and rely on other data, because you can take advantage of the caching nature of computed data and avoid recalculating every time you get a value;
2) 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.
9. How to understand custom instructions?
* Key answers:
The implementation principle of the instruction can be summarized from the compilation principle => code generation => instruction hook implementation
1. When generating the AST syntax tree, directives are encountered to add the cache attribute to the current element
Generate the instruction code by genDirectives
3. Extract the hook of the instruction to CBS before patch, and call the corresponding hook during patch.
4. When executing the corresponding hook function, call the method defined by the corresponding instruction
10. What is the principle of v-Model?
* Key answers:
The V-model is essentially a syntax sugar, which you can think of as the syntax sugar of the value + input method. This can be customized through the Prop and Event properties of the Model property. The native V-Model generates different events and attributes depending on the tag.
The V-Model internally uses different attributes for different input elements and throws different events:
1) Text and Textarea elements use value attributes and input events;
2) Checkbox and radio use checked attributes and change events;
3) Select field value as prop and change as event.
NO6. Constant test – Performance optimization
*Vue performance optimization
1. What Vue performance optimizations have you done? (Statistical results)
1) Coding phase
-
Minimize the data in data, data in data will add getter and setter, will collect the corresponding watcher;
-
Use the event broker if you need to use V-for to bind events to each element;
-
SPA page adopts keep-alive cache component;
-
In more cases, use v-if instead of V-show;
-
Key c.
-
Use routing lazy loading, asynchronous components;
-
Anti-shake, throttling;
-
Import third-party modules on demand;
-
Long list scrolling to visual area for dynamic loading;
-
Lazy loading of images;
2) User experience:
-
Skeleton screen;
-
PWA.
-
You can also use caching (client-side caching, server-side caching) optimization, server-side gZIP compression, and so on.
3) SEO optimization
-
Pre-rendered;
-
Server rendering SSR;
4) Package optimization
-
Compression code;
-
The Tree Shaking/Scope Hoisting;
-
Load third-party modules using CDN;
-
Multithreaded packaging happypack;
-
SplitChunks separate public files;
-
SourceMap optimization;
Participation Information:
Vue. Js technology Revealed:
Ustbhuangyi. Making. IO/vue – analysi…
Vue source code:
github.com/vuejs/vue