Home > Web Front-end > Vue.js > 20+ must-know Vue interview questions (with answer analysis)

20+ must-know Vue interview questions (with answer analysis)

青灯夜游
Release: 2022-05-17 09:41:12
forward
13166 people have browsed it

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.

20+ must-know Vue interview questions (with answer analysis)

[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.

0. Can you talk about MVVM?


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)

1. Briefly talk about the principle of Vue2.x responsive data


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).

2. Do you know the principle of Vue3.x responsive data?


(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)

3. Let’s talk about vue2.x again How to monitor array changes


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

4. Do you know nextTick? What is the implementation principle?


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

  • Promise
  • MutationObserver
  • setImmediate
  • If none of the above works, use setTimeout

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)

5. Let’s talk about the life cycle of Vue


##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

# 6. In which life cycle are your interface requests generally placed?


Interface requests are generally placed in

mounted, but it should be noted that server-side rendering does not support mounted and needs to be placed in created .

7. Let’s talk about Computed and Watch


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 .

8. Let’s talk about the difference between v-if and v-show


When the condition is not established,

v-if will not Rendering DOM elements, v-show operates on the style (display), switching the display and hiding of the current DOM.

9. Why is the data in the component a function?


If a component is reused multiple times, multiple instances will be created. Essentially,

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.

10. Let’s talk about the principle of v-model


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.

11. Let’s talk about the principle of Vue event binding


Native event binding is bound to real elements through

addEventListener. Component event binding is implemented through Vue’s custom $on.

Interviewer: (This kid’s basics are pretty good, I’ll have to get more advanced next)

12. Do you know the principle of Vue template compilation? Can you briefly explain it? ?


Simply put, the compilation process of Vue is the process of converting

template into the render function. It will go through the following stages:

    Generate AST tree
  • Optimization
  • codegen
First parse the template and generate

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)

13. The diff algorithms of Vue2.x and Vue3.x renderers are respectively Let’s talk about it


Simply speaking, the diff algorithm has the following process

  • Compare the same level, and then compare the child nodes
  • First Determine whether one party has child nodes and the other does not (if the new children has no child nodes, remove the old child nodes)
  • Compare the situation where both children have child nodes (core diff)
  • Recursively compare child nodes

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)

14. Let’s talk about the role of virtual Dom and key attributes


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.

15. Do you know about keep-alive?


keep-aliveYou 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)

16. Let’s talk about the calling sequence of component life cycle in Vue


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

17.What are the ways to communicate with Vue2.x components?


    ##Parent-child component communication
  • Parent->Child

    props

    , Child->Parent$on, $emit Get the parent-child component instance

    $parent, $children

    Ref

    Get the instance by calling the component's properties or methods

    Provide, inject

    Officially not recommended, but very commonly used when writing component libraries

    Sibling component communication
  • Event Bus

    Implement cross-component CommunicationVue.prototype.$bus = new Vue

    Vuex

    Cross-level component communication
  • Vuex

    $attrs、$listeners

    Provide、inject

18 .Do you understand SSR?

SSR is server-side rendering.
That is, Vue renders tags into HTML on the client side and completes it on the server side, and then returns the HTML directly to the client. end

.
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:

beforeCreate

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.

19. What performance optimizations have you done on Vue?


Encoding stage

Try to reduce the data in the data, and the data in the data will be Adding getters and setters will collect corresponding watchers
  • 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 caching component
  • In more cases, use v-if instead of v-show
  • key to ensure unique
  • Use routing Lazy loading, asynchronous components
  • Anti-shake, throttling
  • Import third-party modules on demand
  • Scroll the long list into the visible area and load it dynamically
  • Pictures Lazy loading

SEO optimization

Pre-rendering
  • Server-side rendering SSR

Packaging optimization

Compression code
  • Tree Shaking/Scope Hoisting
  • Use cdn to load Third-party module
  • Multi-threaded packaging happypack
  • splitChunks extracts public files
  • sourceMap optimization

User experience

Skeleton screen
  • PWA
  • You can also use cache (client cache, server cache) optimization and server-side enablement gzip compression, etc.

(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

The value of


location.hash

is actually what follows # in the URL.
history is actually implemented using the API provided in HTML5, mainly including

history.pushState()

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 Video

! !

The 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!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template