[Compilation and Sharing] Some Vue high-frequency interview questions
This time I will share with you some common interview questions about Vue to help you sort out the basic knowledge and enhance your Vue knowledge reserve. It is worth collecting, come and take a look!
# What I share are some common Vue interview questions, but they do not represent all. If there is something wrong in the article, please point it out. If you have any doubts or have other interview questions, you can also leave a message in the comment area to share. Let’s discuss it together. Thank you!
1. What are the communication methods for vue2.0 components?
Parent-child component communication:
props
andevent
,v- model
,.sync
,ref
,$parent
and$children
. (Learning video sharing: vue video tutorial)Non-parent-child component communication:
$attr
and$listeners
,provide
andinject
,eventbus
, access through root instance$root
,vuex
,dispatch
andbrodcast
2. How does v-model implement two-way binding?
vue 2.0
v-model
is used to create two-way binding on form controls or components. The essence is the syntactic sugar ofv-bind
andv-on
, in Ifv-model
is used on a component, the component namedvalue
will be bound to the component by default.prop
and an event namedinput
.Vue3.0 In 3.x,
v-model
on a custom component is equivalent to passingmodelValue prop
and receive the thrownupdate:modelValue
event
3. What is the difference between Vuex and a simple global object?
There are two main differences between Vuex and global objects:
Vuex’s state storage is responsive. When the Vue component reads the state from the store, if the store The status in ization, then the corresponding components will be updated efficiently accordingly.
The state in the store cannot be changed directly. The only way to change the state in the store is to commit it explicitly (commit)mutation. This allows us to easily track changes in each state, allowing us to implement some tasks Tools help us better understand our applications.
4. What is the execution order of Vue’s parent component and sub-component life cycle hooks?
Rendering process: The parent component must be mounted only after all the child components are mounted before it is considered a parent component. Mounting is completed, so the parent component is mounted after the sub-component is mounted
beforeCreate -> parentcreated -> beforeMount -> childbeforeCreate -> subcreated -> subbeforeMount -> Submounted -> Parentmounted
Subcomponent update process:
- Affects the parent component: ⼗beforeUpdate -> SubbeforeUpdate-> ;⼼updated -> ◆ updated
- does not affect the parent component: subbeforeUpdate -> subupdated
## Parent component update process:
- affects Subcomponent: ⼗beforeUpdate -> ⼖beforeUpdate->⼼updated -> ⼗
updated
- Does not affect subcomponents: ◆beforeUpdate -> ◗updated
Destruction process: ◗beforeDestroy -> ⼗beforeDestroy -> ⼖ destroyed -> Parentdestroyed
looks like a lot and is difficult to remember. In fact, as long as you understand it, no matter what the situation is, it must be the parent component waiting for the sub-component to complete. Only after it is completed will the corresponding completed hook be executed, and it will be easy to remember5. What are the differences between v-show and v-if?
v-if
will
destroy and rebuild the event listeners and subcomponents of the conditional block during the switching process , if the initial condition is false, nothing will be done until the condition becomes true for the first time. Dyeing module.v-show
Just
switch based on css, regardless of the initial condition Everything will be rendered.
v-if is more expensive to switch, and
v-show is more expensive to initialize rendering.
Large,
is more suitable to use v-show when frequent switching is required, or the part of the DOM to be switched is very complex.
suitable. If you rarely switch after rendering, it is more appropriate to use
v-if.
6. What problems will v-html in Vue cause?
Dynamic rendering of arbitrary HTML on the website,can easily lead to XSS attacks. So it can only be within credibility Use v-html on content and should never be used on user-submitted content.
7. What is the role of key in v-for?
key
is the unique id
assigned to each vnode
.
During the vnode
diff process, you can quickly compare the key
to determine whether
Whether they are the same node, and the uniqueness of key
can be used to generate map
to obtain faster
Get the corresponding node.
After specifying key
in addition, the "in-place reuse" strategy will no longer be used, which can ensure the accuracy of rendering.
.
8. Why v-for and v-if are not recommended to be used together
- When
v-for
andv-if
When in the same node,v- for
has a higher priority thanv-if
, which meansv-if
will be repeated separately Runs in everyv-for
loop. If the array to be traversed is very large, but the actual data to be displayed is very small , which will cause a lot of performance waste. - In this scenario, it is recommended to use
computed
to filter the data first.
9. What is the difference between vue-router hash mode and history mode?
Difference:
In the url display, the hash mode has "#", and the history mode does not
refresh When viewing the page, the hash mode can be loaded normally to the page corresponding to the hash value, but history has no place. If handled correctly, 404 will be returned. Generally, the backend needs to be configured to redirect all pages to the homepage route.
compatibility. Hash can support lower version browsers and IE
10. How are vue-router hash mode and history mode implemented?
- hash mode:
# Changes in the subsequent hash value will not cause the browser to send a request to the server. Not sending a request
If requested, the page will not be refreshed. At the same time, by listening to the hashchange event, you can know what changes have occurred in the hash, and then based on
Hash changes to implement the operation of updating part of the content on the page.
- history mode:
The implementation of history mode is mainly two APIs released by the HTML5 standard, pushState
and
replaceState
, these two APIs can change the url, but will not send a request. This way you can monitor
Listen to url changes to update part of the content on the page.
11. What are the changes in vue3.0 compared to vue2.x?
- Changes in monitoring mechanism (Object.defineProperty —> Proxy)
- Template
- Object-based component declaration method (class)
- Use ts
- Other changes: support for custom renderers, support for Fragment (multiple root nodes) and Protal (in Other parts of the dom (rendering and building content) components, based on treeshaking optimization, provide more built-in functions
12. Can you talk about MVVM?
- MVVM is the abbreviation of
Model-View-ViewModel
, that is,MVC
TheController
evolves intoViewModel
. - The Model layer represents the data model, View represents the UI component, and ViewModel is the bridge between the View and Model layers. Data will be bound to the viewModel layer and automatically render the data into the page. The view changes. Will be notified when viewModel layer updates data.
13. Why is the component data in vue a function that returns an object instead of an object directly?
- If data is defined as an object, this means that all component instances share a copy of data, therefore, no matter which component instance is modified If data is missing, it will affect all component instances.
- The data in the component is written as a function, The data is defined in the form of function return value, so that each complex When a component is used once, a new copy of data will be returned, which is similar to creating a private data space for each component instance, allowing each component instance to maintain its own data. Simply writing it in object form makes it common to all component instances. If you know a piece of data, it will produce a result that changes everything.
14. How computed in Vue is implemented
The process is summarized as follows:
1. When the component is initialized, computed
and data
will be established respectively.
Self-response system, Observer
traverses each attribute setting in data
get/set
Data interception
2. Initializationcomputed
will call the initComputed
function
Register a
watcher
instance and instantiate aDep
message inside The information subscriber is used as a subsequent collection dependency (such aswatcher
of the rendering function or other calculated properties that observe the Changedwatcher
)When a calculated property is called, its
Object.defineProperty
will be triggeredget
Accessor functionCall the
watcher.depend()
method to its own message subscriberdep
Add other properties tosubs
ofwatcher
Call
watcher
##evaluatemethod (to call
watcher's
getmethod) to make itself a subscriber of other
watcher's message subscribers, first assign
watcherto
Dep.target, then After executing the
getterevaluation function, when accessing the properties in the evaluation function (such as Tathagata Self
data,
propsor other
computed), Their
getaccessor functions are also fired, thereby adding the computed property's
watcherto the
watcher's message subscriber## for the property in the evaluation function. #dep
, when these The operation is completed, and finally closeDep.target
and assign it tonull
and Returns the evaluation function result. 3. When a certain attribute changes, trigger the
interception function, and then call its own message subscriber
dep
’s notify
method, over and over
The subs
array of all subscribers wathcer
is saved in the current dep, and one by one
Call the update
method of watcher
method to complete the response update.
If you are asked this question in the interview and the description is unclear, you can directly draw this from the Vue official document Picture, look at the picture An explanation would be better.
- hijack the data
- through
Object.defineProperty
and combine it with Observer patternimplementation. Vue uses Object.defineProperty - to create an
observe
Hijack all properties and convert them intogetter
andsetter
.Each component instance in Vue will correspond to a
watcher - instance, which will be used during component rendering.
During the process, the used
Data properties are collected as dependencies via
getter
. Then when the dependency'ssetter
fires When,watcher
will be notified, causing its associated components to re-render.
- Object.defineProperty
can only hijack the
object's properties
, while Proxy is directlyProxy Object
Due to Object.defineProperty Only properties can be hijacked, and each property of the object needs to be traversed. And Proxy can directly proxy objects. - Object.defineProperty
New properties need to be added manually
Observe
, becauseObject.defineProperty
hijacks the properties of the object, Therefore, when adding attributes, you need to traverse the object again and add new Add properties and then useObject.defineProperty
for hijacking. It is for this reason that using When Vue adds attributes to the array or object indata
, you need to usevm.$set
. Ensure that newly added attributes are also responsive. - Proxy
supports
13 types of interception
operations, which are defineProperty does not have. New standard performance bonus Proxy As a new standard, in the long run, the JS engine will continue to be optimized
- Proxy
, but
getter
andsetter
will basically not be targeted anymore Sexual optimization. - Proxy
Poor compatibility. Currently, there is no complete support for
Proxy
. Polyfill solution with interception method
Vue’s
Observer performs separate processing on the array, compiles the array method, and assigns it to
On the __proto__
attribute of the array attribute, because of the prototype chain
mechanism, the corresponding
I won’t continue to look for the method. The compilation method will include some methods that will increase the index (push,
unshift
, splice
) for manual observation.
The prerequisite for answering this question clearly is to understand the EventLoop process.
- Execute a delayed callback after the next DOM update cycle ends, and use nextTick to obtain it immediately after modifying the data. The updated DOM.
-
nextTick
For the implementation of micro task, it will first check whether it is supported.Promise
, if it is not supported, it will point directly to the macrotask, and the implementation of the macro task will be checked first. Test whether it supportssetImmediate
(supported by higher versions of IE and Etage). If it is not supported, check whether it is supported. Support MessageChannel. If it is still not supported, it will eventually be downgraded tosetTimeout
0; - By default, it will be executed in micro task mode first, because micro task can be executed in one tick. Complete The implementation is completed, and it has better performance in some scenes with redrawing and animation.
- However, due to the high priority of micro task, in some cases, it may be triggered during the event bubbling process, resulting in
Causes some problems, so some places will force the use of macro task (such as
v-on
).
Note: The reason why the callback function of nextTick
is put into the array once
Instead of executing the callback function directly in nextTick
, it is to ensure that multiple calls can be executed within the same tick.
When nextTcik
is executed this time, multiple asynchronous tasks will not be started, but these asynchronous tasks will be compressed into one simultaneous task.
The step task will be executed within the next tick.
19. Vue template compilation principle
The vue template compilation process is divided into 3 stages:
- Step 1: Analysis
Parse the template string to generate AST. The generated AST element nodes have a total of 3 types, 1 is an ordinary element, and 2 is Expression, 3 is plain text.
- Step 2: Optimize the syntax tree
Not all data in the Vue template is responsive, and a lot of data will never be displayed after it is first rendered. changing, then The DOM generated by this part of the data will not change, and we can skip comparing them during the patch process.
This stage will deeply traverse the generated AST tree to detect whether each of its subtrees is a static node. If it is a static node, The DOM they generate never needs to be changed, which greatly optimizes template updates at runtime.
1. Generate code
const code = generate(ast, options)
Use the generate method to generate the render function from ast.
20. Do you know the principle of Vue3.x responsive data?
Vue3.x uses Proxy
instead of Object.defineProperty. Because Proxy can directly monitor the
There are changes to objects and arrays, and there are as many as 13 interception methods. And as a new standard, it will be subject to continuous performance optimization by browser manufacturers.
change.
Proxy will only proxy the first layer of the object, so how does Vue3 handle this problem?
Determine whether the current return value of Reflect.get is Object. If so, use the reactive method as a proxy. This In this way, deep observation is achieved.
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, it is possible to execute the trigger.
21. What performance optimizations have you done on Vue?
Encoding stage
- Try to reduce the data in the data. The data in the data will add getters and setters, and the corresponding watchers will be collected
- v-if and v-for cannot be used together
- If you need to use v-for to bind events to each element, use an event proxy
- SPA page uses keep -alive cache component
- In more cases, use v-if instead of v-show
- key to ensure uniqueness
- Use routing lazy loading, asynchronous components
- Anti-shake, throttling
- Import third-party modules on demand
- Scroll the long list to the visible area and load dynamically
- Lazy loading of pictures
SEO optimization
- Pre-rendering
- Server-side rendering SSR
Packaging optimization
- Compressed code
- Tree Shaking/Scope Hoisting
- Use cdn to load third-party modules
- Multi-threaded packaging happypack
- splitChunks extract public files
- sourceMap optimization
User experience
- Skeleton screen
- PWA
You can also use cache (client cache, server cache) optimization, enable gzip compression on the server, etc.
(Learning video sharing: web front-end development, Basic programming video)
The above is the detailed content of [Compilation and Sharing] Some Vue high-frequency interview questions. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



There are three ways to refer to JS files in Vue.js: directly specify the path using the <script> tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

In Vue.js, lazy loading allows components or resources to be loaded dynamically as needed, reducing initial page loading time and improving performance. The specific implementation method includes using <keep-alive> and <component is> components. It should be noted that lazy loading can cause FOUC (splash screen) issues and should be used only for components that need lazy loading to avoid unnecessary performance overhead.

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

Implement marquee/text scrolling effects in Vue, using CSS animations or third-party libraries. This article introduces how to use CSS animation: create scroll text and wrap text with <div>. Define CSS animations and set overflow: hidden, width, and animation. Define keyframes, set transform: translateX() at the beginning and end of the animation. Adjust animation properties such as duration, scroll speed, and direction.

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses <router-link to="/" component window.history.back(), and the method selection depends on the scene.

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

You can query the Vue version by using Vue Devtools to view the Vue tab in the browser's console. Use npm to run the "npm list -g vue" command. Find the Vue item in the "dependencies" object of the package.json file. For Vue CLI projects, run the "vue --version" command. Check the version information in the <script> tag in the HTML file that refers to the Vue file.

There are three common methods for Vue.js to traverse arrays and objects: the v-for directive is used to traverse each element and render templates; the v-bind directive can be used with v-for to dynamically set attribute values for each element; and the .map method can convert array elements into new arrays.
