Home >Web Front-end >Vue.js >[Compiled and shared] Some common Vue interview questions (with answer analysis)

[Compiled and shared] Some common Vue interview questions (with answer analysis)

青灯夜游
青灯夜游forward
2023-01-29 19:52:082766browse

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!

[Compiled and shared] Some common Vue interview questions (with answer analysis)

Summary of common Vue interview questions

MVVM model?

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.

Vue’s life cycle

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-aliveWhen the cached component is activated
deactivated deactivated keep-aliveWhen 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 mounted
  • Update phase: parent beforeUpdate -> child beforeUpdate -> child updated -> parent updated
  • Destruction phase: parent beforeDestroy -> child beforeDestroy -> child destroyed -> parent destroyed

Vue.$nextTick

Execute 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

##What happens during the Vue instance mounting process?

The mounting process refers to the

app.mount() process. This is an initialization process. It does two things as a whole: Initialization and Establish an update mechanism.

Initialization will create component instances, initialize component states, and create various responsive data.

This step of establishing the update mechanism will immediately execute the update function of the component. This will execute the component rendering function for the first time and execute

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.

Vue’s template compilation principle

There is a unique compiler module in Vue called

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.

Vue’s responsiveness principle

  • The data responsiveness in Vue 2 will be processed differently according to the data type. If it is an object, intercept object property access through

    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:

      Recursive traversal during initialization will cause performance loss;
    • The notification update process requires maintaining a large number of
    • dep instances and watcher Instance, it takes up a lot of additional memory;
    • Adding or deleting object properties cannot be intercepted, and requires APIs such as
    • Vue.set and delete to take effect;
    • The newly generated
    • Map and Set data structures in ES6 are not supported.
  • Vue 3 uses the

    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

  • Concept:

    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.

diff algorithm

1. Concept:

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

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

  • First determine whether the tag of the two nodes are the same. If they are different, delete the node and recreate the node for replacement.
  • tagWhen they are the same, replace the attributes first, and then compare the sub-elements, which are divided into the following situations:
    • When the old and new nodes have sub-elements, use the double pointer method comparing. Compare the old and new head and tail pointers, loop closer to the middle, call 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.
    • The new node has child elements, and the old node has no child elements. Just convert the virtual node of the child element into a real node and insert it.
    • The new node has no child elements, and the old node has child elements, then the child elements are cleared and set to the text content of the new node.
    • When the old and new nodes have no child elements, that is, they are both text nodes, the text content will be compared directly, and if they are different, they will be updated.

#What is the role of key in Vue?

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.

Why is the data in the component a function?

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.

How to communicate between components in Vue?

  • 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); refYou 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.

What is the difference between v-show and v-if?

  • 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-ifSwitching 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-showWhen changing from false to true, the life cycle of the component will not be triggered; v-ifWhen 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.

  • Performance consumption is different.
  • v-if

    has a higher switching cost; v-show has a higher initial rendering cost.

  • Usage scenarios:
If you need to switch very frequently, it is better to use

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.

What is the difference between computed and watch?

    computed
  • Computed properties rely on other properties to calculate values. Changes in any internal dependencies will re-execute the function. Computed properties are cached and can be reused multiple times. When calculating attributes, the return value will be obtained from the cache. The calculated attributes must have the return keyword.
  • watch
  • Listen to changes in certain data to trigger the function. When the data is an object type, you need to use the deep listening 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.
  • Application scenarios:
Computed properties are generally used in template rendering. A certain value depends on other response objects or even calculated properties; while listening properties are suitable for observing a certain value. Change to complete a complex business logic.


Why are v-if and v-for not recommended to be used together?

In Vue 2,

v-for

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.

v-if

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 filter items in the list, for example:
    v-for = "user in users" v-if = "user.active"
  • . In this case, you can define a calculated property and let it return the filtered list. In order to avoid rendering the list that should be hidden, such as
  • v-for = "user in users" v-if = "showUsersFlag"
  • . In this case, you can move v-if to the container element or wrap it with a layer of template.
$set

You can manually add responsive data to solve the problem of data change views not being updated. When you directly set the value of an item in the array or directly set the value of a property of the object in the project, you will find that the page is not updated. This is because of the limitations of

Object.defineProperty()

, 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-aliveThe 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.

  • You can set the following attributes:
    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.
    Matching first checks the 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.

    Usage scenarios: Some identical or similar codes are often used in different components, and the functions of these codes are relatively independent. The same or similar code can be extracted through mixins. Disadvantages:

    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.

    • Slot
    • slot
    • The slot is generally used inside the component. When encapsulating the component, it is not used inside the component. When determining what form of element is displayed in this position, you can occupy this position through
    slot

    . The element at this position needs to be passed in the form of content from the parent component. slot is divided into:

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

    <slot> of the child component.
      Tag position. If the parent component is used without passing content to the slot, the backing content will be displayed on the page.
    • 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
    • . When used in the parent component, the
    • v-slot 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 slotnameAttribute value. Use the v-slot directive to specify which slot the element is placed in. It must match the