Home > Article > Web Front-end > [Compiled and shared] Some common Vue interview questions (with answer analysis)
This time I will share with you some common interview questions about Vue to help you sort out basic knowledge and enhance your Vue knowledge reserve. It is worth collecting, come and take a look!
MVVM is the abbreviation of Model-View-ViewModel
, which is essentially an upgraded version of the MVC
model. Among them, Model
represents the data model, View
represents the page seen, and ViewModel
is between View
and Model
Bridge, 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. In the past, the view was updated by operating DOM
, but now it is data-driven view
.
Each Vue component instance will go through a series of initialization processes after it is created. During this process, a function called a life cycle hook will be run. This gives users the opportunity to add their own code at specific stages.
The life cycle of Vue can be divided into 8 stages: before and after creation, before and after mounting, before and after updating, before and after destruction, as well as the life cycle of some special scenarios. Vue 3 also adds three new scenes for debugging and server-side rendering. [Related recommendations: vuejs video tutorial, web front-end development]
Life cycle in Vue 2 | Lifecycle in Vue 3 | Description |
---|---|---|
beforeCreate |
beforeCreate |
Before creation, the data of data and methods have not been initialized yet |
created |
created |
After creation, there is a value in data , but it has not been mounted yet. You can do some Ajax Request |
beforeMount |
beforeMount |
before mounting, the virtual DOM will be found , compiled into Render
|
mounted |
mounted |
After mounting, DOM has been created and can be used to obtain access data and DOM elements |
beforeUpdate |
beforeUpdate |
Before update, can be used to obtain various statuses before update |
updated | updated |
After updating, all statuses are up to date |
beforeDestroy |
beforeUnmount |
Can be used to cancel some timers or subscriptions before destruction |
destroyed |
unmounted |
After destruction, it can be used for the cancellation of some timers or subscriptions |
activated |
activated |
keep-alive When the cached component is activated |
deactivated |
deactivated |
keep-alive When the cached component is deactivated |
errorCaptured |
errorCaptured |
Called when capturing an error from a descendant component |
— | renderTracked |
Debug hook, called when reactive dependencies are collected |
— | renderTriggered |
Debug hook, called when reactive dependency is triggered |
— | serverPrefetch |
before the component instance is rendered on the server transfer |
Life cycle of parent and child components:
Loading and rendering phase
: parent beforeCreate -> parent created -> parent beforeMount - > child beforeCreate -> child created -> child beforeMount -> child mounted -> parent mountedUpdate phase
: parent beforeUpdate -> child beforeUpdate -> child updated -> parent updatedDestruction phase
: parent beforeDestroy -> child beforeDestroy -> child destroyed -> parent destroyedExecute a delayed callback after the next DOM update cycle. Use this method immediately after modifying data to get the updated DOM.
nextTick
is a global API provided by Vue. Due to Vue's asynchronous update strategy, our data modifications will not be directly reflected in the DOM. At this time, if you want To immediately obtain the updated DOM state, you need to use this method.
Vue executes asynchronously when updating the DOM. When data changes, Vue will open an asynchronous update queue and buffer all data changes that occur in the same event loop. If the same watcher
is triggered multiple times, it will only be pushed into the queue once. This deduplication during buffering is important to avoid unnecessary calculations and DOM operations. The nextTick
method will add a callback function to the queue to ensure that the function is called only after the previous DOM operation is completed.
Usage scenarios:
If you want to get the updated DOM
structure immediately after modifying the data, you can use Vue.nextTick ()
Perform DOM
operations in the created
life cycle
app.mount() process. This is an initialization process. It does two things as a whole:
Initialization and
Establish an update mechanism.
patchConvert
vnode to
dom ; At the same time, executing the rendering function for the first time will create a dependency between its internal responsive data and the component update function, so that when the data changes in the future, the corresponding update function will be executed.
compiler. Its main function is to compile users The written
template is compiled into an executable
render function in js.
In Vue, the compiler will first parse
template, this step is called
parse, and after the end, a JS object will be obtained, which is called
abstract syntax tree AST; Then there is the conversion process of deep processing of
AST, this step is called
transform, and finally the
AST obtained previously is generated into JS code, also It’s the
render function.
Object.defineProperty(obj,key,descriptor). When the data is accessed or changed, sense and react; if it is an array, overwrite the array prototype. method, extending its seven change methods (push, pop, shift, unshift, splice, sort, reverse) so that these methods can additionally perform update notifications and respond.
Disadvantages:
instances and
watcher Instance, it takes up a lot of additional memory;
and
delete to take effect;
and
Set data structures in
ES6 are not supported.
Proxy mechanism of
ES6 to proxy data that needs to be responsive. It can support objects and arrays at the same time. Dynamic attribute additions and deletions can be intercepted. All new data structures are supported. Object nested attributes are recursive at runtime and are proxied only when used. There is no need to maintain a particularly large number of dependencies, and the performance has been greatly improved. Big progress.
Virtual DOM, as the name suggests, is a virtual DOM object, which itself is A JS object just describes a view structure through different attributes.
Benefits of virtual DOM:
(1) Performance improvement
There are limitations to directly operating the DOM. There are many attributes on a real element. If you operate it directly, it will A lot of extra attribute content is manipulated, which is unnecessary. If these operations are transferred to JS objects, it will be much simpler. In addition, operating the DOM is relatively expensive, and frequent DOM operations can easily cause page redrawing and reflow. If intermediate processing is performed through abstract VNode, the number of direct DOM operations can be effectively reduced, thereby reducing page redrawing and reflow.
(2) Convenient cross-platform implementation
The same VNode node can be rendered into corresponding content on different platforms. For example: when rendered in the browser, it is a DOM element node, and when rendered in Native (iOS, Android) it becomes the corresponding control. . Vue 3 allows developers to implement custom renderers based on VNode to facilitate rendering for different platforms.
Structure:
There is no unified standard, generally including tag
, props
, children
Three items. tag
: required. It's a label, or it can be a component, or a function. props
: Optional. It's the properties and methods on this label. children
: Optional. It is the content or child nodes of this tag. If it is a text node, it is a string; if it has child nodes, it is an array. In other words, if children
is judged to be a string, it means that it must be a text node, and this node must have no child elements.
1. Concept:
diff
The algorithm is a Comparison algorithm, by comparing the old virtual DOM and the new virtual DOM, we can find out which virtual node has changed. Find this virtual node and only update the real node corresponding to this virtual node without updating other unchanged nodes. Node to accurately update the real DOM, thus improving efficiency.
2. Comparison method:
diff
The overall strategy of the algorithm is: Depth first, same layer comparison
. Comparisons will only be performed at the same level, and will not be compared across levels; during the comparison process, the loop will shrink from both sides to the middle.
tag
of the two nodes are the same. If they are different, delete the node and recreate the node for replacement. tag
When they are the same, replace the attributes first, and then compare the sub-elements, which are divided into the following situations: patchVnode
according to the situation, patch
repeat the process, call createElem
to create a new node, and create a new node from the hash table Find the key
consistent VNode
node and then operate according to the situation. key
is mainly used to update the virtual DOM
more efficiently.
When Vue determines whether two nodes are the same, it mainly determines the key
and element type tag
of the two nodes. Therefore, if key
is not set, its value is undefined, and it may always be considered that these are two identical nodes, and only update operations can be performed, which will cause a large number of DOM update operations.
In new Vue(), it can be a function or an object, because there is only one root instance and no data pollution will occur.
In the component, data must be a function. The purpose is to prevent multiple component instance objects from sharing the same data and causing data pollution. In the form of a function, it will be returned as a factory function when initData is used. Brand new data object.
Communication between parent and child components:
The parent passes data to the child through props
, and the child passes data to the parent through $emit
Trigger events; communication can also be done through the parent chain/child chain ($parent
/$children
); ref
You can also access component instances; provide
/inject
;$attrs
/$listeners
.
Sister component communication:
Global event busEventBus
, Vuex
.
Cross-level component communication:
Global event busEventBus
, Vuex
, provide
/ inject
.
The control methods are different. v-show
is by adding the css attribute display: none
to the element, but the element still exists; while v-if
controls the display or hiding of the element by changing the entire element Add or delete.
The compilation process is different. v-if
Switching has a partial compilation/uninstallation process. During the switching process, internal event listeners and sub-components are properly destroyed and rebuilt; v-show
is just a simple css-based switching.
The compilation conditions are different. v-if
is a true conditional rendering. It will ensure that event listeners and subcomponents within the conditional block are properly destroyed and rebuilt during the switching process. When the rendering condition is false, no operation will be performed until Render for the sake of truth.
The trigger life cycle is different. v-show
When changing from false to true, the life cycle of the component will not be triggered; v-if
When changing from false to true, the component's beforeCreate## will be triggered. #,
created,
beforeMount,
mounted hooks trigger the component's
beforeDestory,
destoryed# when changing from true to false. ##hook.
has a higher switching cost; v-show
has a higher initial rendering cost.
v-show
, such as: accordion menu, tab page, etc.;
If the conditions rarely change during runtime, it is better to use v-if
. For example, after the user logs in, different content will be displayed according to different permissions.
return
keyword.
deep
attribute when the attribute value in the object changes. You can also use the immediate listening immdiate
attribute when the page is first loaded.
has a higher priority than v-if
, which means v-if
will Repeatedly run in each v-for
loop. If the array to be traversed is large and the actual data to be displayed is very small, it will cause a huge waste of performance. In Vue 3, it is exactly the opposite.
has a higher priority than v-for
, so when v-if
is executed , the variable it calls does not exist yet and will cause an exception. There are usually two situations that lead to this:
In order to avoid rendering the list that should be hidden, such as v-if
to the container element or wrap it with a layer of template
.
, which cannot monitor data changes. You can use this.$set(array or object, array subscript or object’s property name, updated value )
solve. <h3 data-id="heading-17"><strong>What is keep-alive? </strong></h3>
<ul>
<li>Function: Implement component caching, maintain component status, and avoid performance problems caused by repeated rendering. </li>
<li>Working principle: Vue.js internally abstracts DOM nodes into individual VNode nodes. <code>keep-alive
The cache of components is also based on VNode nodes. It caches components that meet the conditions in the cache object, and when re-rendering, the VNode node is taken out of the cache object and rendered.
include
: string or regular, only components with matching names will be cached. exclude
: String or regular expression, any component with a matching name will not be cached. max
: Number, the maximum number of component instances that can be cached. name
option of the component. If the name
option is not available, it matches its local registration name (the key value of the parent component components option). Anonymous components cannot be match. Components with keep-alive
cached will have two more life cycle hooks: activated
, deactivated
.
When entering the component for the first time: beforeCreate --> created --> beforeMount --> mounted --> activated --> beforeUpdate --> updated --> deactivated
Enter the component again It provides A very flexible way to distribute reusable functionality in Vue components.
Unclear variable source
Multiple mixins may cause naming conflicts (solution: Vue 3 Combination API)
There are multiple pairs of relationships between mixin and component pits, making the project more complex.
##Default slot
: Subcomponents use the <slot>
tag to determine the rendering position, label You can put the DOM
structure inside as backup content. When the parent component is in use, you can directly write content in the tag of the child component, and this part of the content will be inserted into the
Named slot: The subcomponent uses the
name attribute to represent the name of the slot. If the slot does not specify
name, there will be a hidden The included name is
default directive is used to specify which slot the element needs to be placed in based on the default slot. The
v-slot value is the child component slot
nameAttribute value. Use the
v-slot directive to specify which slot the element is placed in. It must match the
element, and one
element can only correspond to A reserved slot, that is, multiple
elements cannot use the
v-slot directive to specify the same slot. The abbreviation of
v-slot is
#. For example,
v-slot:header can be abbreviated as
#header.
Scope slot: The subcomponent binds
props data on the
<slot> tag to pass the subcomponent data to Used by the parent component. Method for parent component to obtain slot binding props data:
scope="received variable name":
#What are the modifiers in Vue?
Form modifierlazy
After filling in the information, the value will be assigned to value only when the cursor leaves the label, that is, change
Information synchronization is performed after the event. number
Automatically converts the user input value into a numeric type, but if the value cannot be parsed by parseFloat
, the original value will be returned. trim
Automatically filter the first and last spaces entered by the user, while the spaces in the middle will not be filtered.
Event modifierstop
prevents event bubbling, 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
The handler function is only triggered when event.target
is the current element itself. once
After the event is bound, it can only be triggered once, and it will not be triggered the second time. capture
Use the event capture mode, that is, events triggered by the element itself are processed here first, and then handed over to internal elements for processing. passive
Tell the browser that you don't want to block the default behavior of the event. native
Let the component listen to the native events of the root element like the html
built-in tag. Otherwise, using v-on
on the component will only listen to custom events. event.
Mouse button modifierleft
Left click. right
Right click. middle
Middle click.
Key value modifier
Keyboard modifier is used to modify keyboard events (onkeyup
, onkeydown
), There are as follows: keyCode
There are many, but vue
provides us with aliases, which are divided into the following two types:
Concept: SPA (Single-page application)
, that is, single-page application, which is a model of a network application or website , interact with the user by dynamically rewriting the current page. This method avoids interrupting the user experience when switching between pages. In SPA
, all necessary code (HTML, JavaScript, and CSS) is retrieved through the load of a single page, or appropriate resources are dynamically loaded and added to the page as needed (usually in response to user actions). The page does not reload at any point in time, nor does control transfer to other pages. For example, just like a cup, it contains milk in the morning, coffee at noon, and tea in the afternoon. It always has the content and the cup remains unchanged. The difference between
SPA
and MPA
: MPA (Muti-page application)
, that is, multi-page application. In MPA
, each page is a main page and is independent. Whenever a page is accessed, the Html, CSS, and JS files need to be reloaded, and public files are loaded on demand. .
MPA | ||
---|---|---|
One main page and multiple page fragments | Multiple main pages | |
hash mode | history mode | |
Difficult to implement, can be improved by using SSR method | Easy to implement | |
Easy | Transfer through url, cookie, localStorage, etc. | |
Fast speed , Good user experience | Switching loading resources, slow speed, poor user experience | |
Relatively easy | Relatively complex |
The above is the detailed content of [Compiled and shared] Some common Vue interview questions (with answer analysis). For more information, please follow other related articles on the PHP Chinese website!