This article has compiled 20 Vue interview questions to share with you, along with an analysis of the answers. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
[Recommended related interview questions: vue interview questions (2021)]
From the thickness of the lens When I saw the yellow and black plaid shirt, I realized that the interviewer sitting in front of me must have come with bad intentions.
As usual, I am going to spend 3 minutes introducing myself. During this period, to avoid embarrassment, I stared between the interviewer's eyebrows, but the interviewer was obviously not very interested in my experience. He interrupted me at the 1 and a half minute mark.
What technology stack do you think you are best at?
Vue, I like Youda very much. Vue’s first documentary was just released recently. It’s really good to watch.
MVVM is the abbreviation of Model-View-ViewModel
, which is the evolution of Controller
in MVC
into ViewModel
. The Model layer represents the data model, the View represents the UI component, and the ViewModel is the bridge between the View and Model layers. The data will be bound to the viewModel layer and automatically render the data into the page. When the view changes, the viewModel layer will be notified to update the data. (Learning video sharing: vue video tutorial)
Vue is When initializing data, Object.defineProperty
will be used to redefine all properties in the data. When the page uses the corresponding properties, dependency collection will first be performed (collecting the watcher
of the current component). If the property When changes occur, relevant dependencies will be notified for update operations (Publish and Subscribe
).
(Fortunately, I have read it, this is not a problem for me)
Vue3.x uses Proxy
instead of Object.defineProperty . Because Proxy can directly monitor changes in objects and arrays, and has as many as 13 interception methods. And as a new standard, it will be subject to continuous performance optimization by browser manufacturers.
Proxy will only proxy the first layer of the object, so how does Vue3 deal with this problem?
(Very simple)
Determine whether the current return value of Reflect.get is Object. If so, use the reactive
method to act as a proxy.
This way Achieved deep observation.
When monitoring an array, get/set may be triggered multiple times, so how to prevent multiple triggers?
We can determine whether the key is the attribute of the current proxied object target itself, or whether the old value and the new value are equal. Only when one of the above two conditions is met, the trigger can be executed.
The interviewer raised his head. I thought to myself
(This guy is okay, better than the previous two, he should have read the source code of Vue3 more or less)
uses function hijacking to rewrite the array method. Vue rewrites the prototype chain of the array in data and points to the array prototype defined by itself. method. In this way, dependency updates can be notified when the array api is called. If the array contains reference types, the reference types in the array will be traversed recursively again for monitoring. This enables monitoring of array changes.
(Interviewers who can ask this question pay more attention to depth, and these routine operations should be remembered)
(For details of the prototype chain, please refer to my other article Column)
This article will help you thoroughly understand the JavaScript prototype chain
Execute the delayed callback after the next DOM update cycle. nextTick mainly uses macro tasks and micro tasks. Depending on the execution environment, try using
An asynchronous method is defined. Calling nextTick multiple times will store the method in the queue, and clear the current queue through this asynchronous method.
(For information about macro tasks, micro tasks and event loops, please refer to my other two columns)
(You will find after seeing this, in fact, asking the framework will ultimately test you. Basic JavaScript skills)
##beforeCreate is triggered after new Vue() For the first hook, the data and methods on data, methods, computed and watch cannot be accessed in the current stage.
createdOccurs after the instance is created. Data observation has been completed at the current stage, that is, the data can be used and changed. Changing the data here will not trigger the updated function. You can do some initial data acquisition. You cannot interact with the Dom at the current stage. If you have to, you can access the Dom through vm.$nextTick.
beforeMountOccurs before mounting, before which the template template has been imported and compiled with rendering functions. At the current stage, the virtual Dom has been created and is about to start rendering. Changes to the data can also be made at this time, and updated will not be triggered.
mountedOccurs after the mounting is completed. At the current stage, the real Dom is mounted, the data is bidirectionally bound, the Dom node can be accessed, and the Dom can be accessed using the $refs attribute. operate.
beforeUpdate Occurs before the update, that is, the responsive data is updated and the virtual dom is triggered before re-rendering. You can change the data in the current stage without causing re-rendering.
updatedOccurs after the update is completed, and the component Dom in the current stage has been updated. Be careful to avoid changing data during this period as this may result in an infinite loop of updates.
beforeDestroyOccurs before the instance is destroyed. The instance can be fully used at the current stage. We can perform post-processing finishing work at this time, such as clearing the timer.
destroyedOccurs after the instance is destroyed. At this time, only the dom shell is left. The component has been disassembled, the data binding has been removed, the listener has been removed, and all child instances have been destroyed.
(If you are interested in the detailed explanation of Vue’s life cycle, please refer to my other column)Interpret the Vue life cycle from the source code to let the interviewer understand Are you impressed
mounted, but it should be noted that server-side rendering does not support mounted and needs to be placed in
created .
Computed is essentially a watcher with cache, and the dependent properties occur Changes will update the view.
Suitable for computing scenarios where calculations consume relatively high performance. When the expression is too complex, putting too much logic in the template will make the template difficult to maintain. You can put the complex logic into calculated properties.
WatchThere is no cache, it is more of an observation function, and you can monitor certain data and execute callbacks. When we need to deeply monitor the properties in the object, we can turn on the
deep: true option, so that each item in the object will be monitored. This will cause performance problems. For optimization, you can use
string form to monitor. If it is not written to the component, don't forget to use
unWatch to manually log out .
v-if will not Rendering DOM elements,
v-show operates on the style (display), switching the display and hiding of the current DOM.
these instances all use the same constructor. If data is an object, the object is a reference type and will affect all instances. So in order to ensure that data does not conflict between different instances of the component, data must be a function.
v-model is essentially a syntax sugar, you can see It is the syntactic sugar for the
value input method.
Can be customized through the
prop and
event attributes of the model attribute. The native v-model will generate different events and attributes based on different tags.
addEventListener. Component event binding is implemented through Vue’s custom
$on.
template into the
render function. It will go through the following stages:
AST syntax tree (a form of JavaScript object to describe the entire template).
Use a large number of regular expressions to parse the template, and when encountering labels and text, corresponding hooks will be executed for related processing.
Vue's data is responsive, but in fact not all data in the template is responsive. Some data will not change after it is first rendered, and the corresponding DOM will not change either. Then the optimization process is to deeply traverse the AST tree and mark the tree nodes according to relevant conditions. We can skip comparing
these marked nodes (static nodes), which will greatly optimize the runtime template.
The last step of compilation is to convert the optimized AST tree into executable code
.
Interviewer: (Spiritual guy, you have something, the difficulty will be increased. If you don’t believe it, it won’t be difficult for you)
Simply speaking, the diff algorithm has the following process
The time complexity of normal Diff between two trees is O(n^3)
, but in actual situations we rarely perform cross Hierarchical mobile DOM
, so Vue optimizes Diff from O(n^3) -> O(n)
. It is only needed when the old and new children are multiple child nodes. The core Diff algorithm performs same-level comparisons.
The core Diff algorithm of Vue2 adopts the double-end comparison
algorithm. At the same time, it compares from both ends of the old and new children, uses the key value to find the reusable node, and then performs related operations. . Compared with React's Diff algorithm, under the same circumstances, it can reduce the number of mobile nodes, reduce unnecessary performance losses, and is more elegant.
Vue3.x draws on the
ivi algorithm and the inferno algorithm
to determine its type when creating a VNode, and mount/patch
uses bit operations
to determine the type of a VNode. On this basis, combined with the core Diff algorithm, the performance is improved compared to Vue2.x. (The actual implementation can be viewed in conjunction with the Vue3.x source code.)
This algorithm also uses the idea of dynamic programming
to solve the longest recursive subsequence.
(After seeing this, you will also find that the charm of data structures and algorithms is everywhere in the framework)
Interviewer: (Okay, okay, it seems to be a seedling, but I would like to introduce myself. It’s really a bit boring, next question)
(Basic, don’t do 6)
Because operating DOM in the browser is very expensive. Frequent operations on the DOM will cause certain performance problems. This is the reason
of virtual Dom.
Vue2’s Virtual DOM draws on the implementation of the open source library snabbdom
.
The essence of Virtual DOM is to use a native JS object to describe a DOM node. It is a layer of abstraction from the real DOM.
(That is, the VNode class in the source code, which is defined in src/core/vdom/vnode.js.)
VirtualDOM mapping to the real DOM must go through the create, diff, patch and other stages of VNode.
The role of key is to reuse DOM elements as much as possible.
When only the order of the nodes in the old and new children is different, the best operation should be to achieve the purpose of updating by moving the position of the element.
It is necessary to save the mapping relationship in the nodes of the old and new children so that reusable nodes can be found in the nodes of the old children. The key is the unique identifier of the node in children.
keep-alive
You can implement component caching. When components are switched, the current Component is uninstalled.
Two commonly used attributesinclude/exclude
allow components to be cached conditionally.
Two life cyclesactivated/deactivated
, used to know whether the current component is active.
keep-alive also uses the LRU (Least Recently Used)
algorithm.
(It’s data structure and algorithm again. It turns out that algorithms also have so many applications on the front end)
The calling order of components is first parent then son
, and the order of rendering completion is first son then parent
.
The destruction operation of components is first the parent, then the son
, and the order of completion of destruction is first the son, then the parent
.
Loading rendering process
Parent beforeCreate->Parent created->Parent beforeMount->Child beforeCreate-> Child created->child beforeMount- >child mounted->parent mounted
Sub component update process
Parent beforeUpdate->Child beforeUpdate->Child updated->Parent updated
Parent component update process
parentbeforeUpdate -> parent updated
Destruction process
##parent beforeDestroy->child beforeDestroy->child destroyed->parent destroyed
Parent->Child
props, Child->Parent$on, $emit
Get the parent-child component instance
Get the instance by calling the component's properties or methods
Officially not recommended, but very commonly used when writing component libraries
Implement cross-component CommunicationVue.prototype.$bus = new Vue
.
SSR has the advantages of better SEO and faster first screen loading speed. However, it also has some shortcomings. For example, our development conditions will be limited. Server-side rendering only supports two hooks:
and created
. Special processing is required when we need some external extension libraries. , server-side rendering applications also need to be in the Node.js running environment. There is also a greater load demand on the server.
Encoding stage
SEO optimization
Pre-renderingPackaging optimization
Compression codeUser experience
Skeleton screen(Optimization is a big project and will involve many aspects. Please open another column here)
20. Let’s talk about the implementation principles of hash routing and history routing is actually what follows # in the URL.
history is actually implemented using the API provided in HTML5, mainly including
and history.replaceState()
. The interviewer picked up the cold coffee next to him and took a sip.
(Can’t I ask this guy more questions?)
For more programming-related knowledge, please visit:
Programming VideoThe above is the detailed content of 20+ must-know Vue interview questions (with answer analysis). For more information, please follow other related articles on the PHP Chinese website!