Home > Web Front-end > Vue.js > body text

[Compilation and Sharing] Some Vue high-frequency interview questions

青灯夜游
Release: 2022-08-25 18:58:48
forward
1730 people have browsed it

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!

[Compilation and Sharing] Some Vue high-frequency interview questions

# 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 and event, v- model, .sync, ref, $parent and $children. (Learning video sharing: vue video tutorial)

  • Non-parent-child component communication: $attr and $listeners, provide and inject, eventbus, access through root instance $root, vuex, dispatch and brodcast

2. How does v-model implement two-way binding?

  • vue 2.0v-model is used to create two-way binding on form controls or components. The essence is the syntactic sugar of v-bind and v-on, in If v-model is used on a component, the component named value will be bound to the component by default. prop and an event named input.

  • Vue3.0 In 3.x, v-model on a custom component is equivalent to passing modelValue prop and receive the thrown update: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:

  1. Affects the parent component: ⼗beforeUpdate -> SubbeforeUpdate-> ;⼼updated -> ◆ updated
  2. does not affect the parent component: subbeforeUpdate -> subupdated

## Parent component update process:

    affects Subcomponent: ⼗beforeUpdate -> ⼖beforeUpdate->⼼updated -> ⼗ updated
  1. 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 remember

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

So,

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

  • Whenv-for and v-if When in the same node, v- for has a higher priority than v-if, which means v-if will be repeated separately Runs in every v-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 The Controller evolves into ViewModel.
  • 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 a Dep message inside The information subscriber is used as a subsequent collection dependency (such as watcher of the rendering function or other calculated properties that observe the Changed watcher )

  • When a calculated property is called, its Object.defineProperty will be triggered get Accessor function

  • Call the watcher.depend() method to its own message subscriber dep Add other properties to subs of watcher

  • Call watcher ##evaluate method (to call watcher's get method) to make itself a subscriber of other watcher's message subscribers, first assign watcher to Dep.target , then After executing the getter evaluation function, when accessing the properties in the evaluation function (such as Tathagata Self data , props or other computed ), Their get accessor functions are also fired, thereby adding the computed property's watcher to the watcher's message subscriber## for the property in the evaluation function. #dep, when these The operation is completed, and finally close Dep.target and assign it to null and Returns the evaluation function result.

  • 3. When a certain attribute changes, trigger the
set

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.

15. The responsive principle of Vue

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.

[Compilation and Sharing] Some Vue high-frequency interview questions

Vue's responsiveness is to
    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 into getter and setter. 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's setter fires When, watcher will be notified, causing its associated components to re-render.
16. What are the disadvantages of Object.defineProperty?

  • Object.defineProperty

    can only hijack the object's properties, while Proxy is directly Proxy ObjectDue 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, because Object.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 use Object.defineProperty for hijacking. It is for this reason that using When Vue adds attributes to the array or object in data, you need to use vm.$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 and setter will basically not be targeted anymore Sexual optimization.

  • Proxy

    Poor compatibility. Currently, there is no complete support for Proxy. Polyfill solution with interception method

17. How to detect array changes in Vue2.0?

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.

18. What is nextTick used for and what is its principle?

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 supports setImmediate (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 to setTimeout 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)
Copy after login

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!

Related labels:
source:juejin.cn
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!