takeaway
Some basic knowledge of VUE, as well as the relevant implementation principle, has been a popular topic in the interview, this paper combs the common VUE interview questions. The series of articles will be published on the public account “Front-end Xiaoyuan”, which can be added by scanning the QR code at the bottom of the article on wechat.
Note: on the underlying implementation principle, it is best to learn by referring to the source code, some principles are relatively complex, it is difficult to understand deeply through an article, and finally may be only a little knowledge, when the interview in-depth questions, it is revealed. This paper is mainly to sort out the possible aspects of Vue pilot, usually should pay attention to the accumulation and reserve of knowledge, in order to cope with the job and interview with ease, some questions will give relevant links for detailed study.
Component communication related problems
1. What are the communication modes of components?
Parent-child component communication:
Props and Event, V-model,.sync, ref, $parent, and $children
Non-parent component communication:
$attr and $Listeners, provide and inject, eventBus, access via root instance $root, vuex, Dispatch, and Brodcast
Communication mode belongs to the more basic interview questions, specific can refer to my article – VUE component communication see this article is enough
2. Why can’t child components modify Prop passed by parent components?
Vue advocates one-way data flow, where updates to the parent props flow to the child components, but not the other way around. This is to prevent accidental changes in the state of the parent component, making the application’s data flow difficult to understand. Debugging can be costly when applications are complex if one-way data flows are broken.
3. How does V-Model achieve bidirectional binding?
V-model is used to create bidirectional bindings on form controls or components. It is essentially a syntagmatic candy of V-bind and V-ON. Using v-Model on a component binds a prop named Value and an event named input to the component by default. Article – VUE component communication is described in detail in this article
4. What is the difference between Vuex and pure global objects?
There are two main differences between Vuex and global objects:
- Vuex’s state storage is reactive. When the Vue component reads the state from the Store, if the state in the store changes, the corresponding component is updated efficiently accordingly.
- You cannot change the state in the store directly. The only way to change the state in a store is to commit mutation explicitly. This allows us to easily track each state change, which allows us to implement tools that help us better understand our application.
5. Why can’t asynchronous operation be performed in Vuex mutation?
The only way for any state update in Vuex is mutation, and the asynchronous operation is implemented by submitting mutation via Action. This allows us to easily track each state change, which allows us to implement tools that help us better understand our application.
Each mutation was updated with a new state change so devTools could take a snapshot and then implement time-travel. If mutation supported asynchronous operations, there was no way to know when the state was updated, and no tracking of the state was possible, making debugging difficult. Reference especially greatly answer: www.zhihu.com/question/48…
Life cycle related issues
1. What lifecycle hooks do Vue components have?
BeforeCreate, created, beforeMount, Mounted, beforeUpdate, updated, beforeDestroy, and destroyed.
has its own separate hook functions activated and deactivated.
2. What is the sequence of parent and child Vue lifecycle hooks?
Rendering process: The parent component must be mounted after all the child components are mounted. -> Parent beforeCreate -> Parent created -> parent beforeMount -> child beforeCreate -> child created -> child beforeMount -> Child mounted -> parent mounted
Sub-component update process:
- Affects the parent component: Parent beforeUpdate-> child beforeUpdate-> Child updated -> Parent updTED
- Does not affect parent component: child beforeUpdate -> Child updated
Parent component update process:
- Affects child components: Parent beforeUpdate-> child beforeUpdate-> Child updated -> Parent updTED
- Does not affect child components: parent beforeUpdate -> Parent updated
Destroy process: Parent beforeDestroy -> Child beforeDestroy -> Child destroyed -> Parent destroyed
A lot of it may seem hard to remember, but it’s easy to remember that in either case, the parent must wait for the child to complete before executing its own completed hook.
The function of related attributes & Comparison of similar attributes
1. What are the differences between V-show and V-IF?
V-if destroys and rebuilds the conditional block’s event listeners and subcomponents during the switch, does nothing if the initial condition is false, and does not begin rendering the module until the condition is true for the first time. V-show just switches based on CSS and renders regardless of the initial conditions. Therefore, v-if switching is more expensive, whereas V-show initial rendering is more expensive, and v-show is more appropriate when switching is required frequently, or when part of the DOM to switch is complex. V-if is more appropriate for rendering that rarely switches.
What is the difference between computed and watch?
Computed attributes, which depend on computed values of other attributes, are cached and updated only when the dependent values change. Watch performs some logic in the callback when the listening properties change. Therefore, computed is suitable for template rendering, where a value depends on other responsive objects or even computed attributes, while Watch is suitable for monitoring the change of a value to complete a complex business logic.
3. computed vs methods
Computed properties are cached based on their reactive dependencies and evaluated only when the dependency changes, whereas methods are executed each time.
4. What is the function of keep-alive?
Keep-alive can save the state of the component it wraps when it switches, preventing it from being destroyed and preventing multiple renders. It has two separate lifecycle hook functions, Actived and Deactived. Components wrapped with keep-alive are not destroyed during switching, but are cached in memory and execute the Deactived hook function, which executes after hitting the cache rendering.
5. What problems can V-HTML cause in Vue
Dynamically rendering arbitrary HTML on a web site can easily lead to XSS attacks. So use V-HTML only for trusted content, and never for user-submitted content.
Principle analysis related topics
This part of the interview questions, only look at the answer part is not enough, the best combination of source code to analyze, you can have a deeper understanding. I’ll link to some of the source code I’ve analyzed in previous articles.
1. The responsive principle of Vue
If you are asked this question in an interview and you are not sure how to describe it, you can draw the picture from the official Vue document to explain it better.
Object.defineProperty
Object.defineProperty
observe
getter
setter
watcher
getter
setter
watcher
2. What are the disadvantages of Object.defineProperty?
Why does Vue3.0 use proxy to implement responsiveness? It’s all a reactive comparison of Object.defineProperty and proxy implementations.
Object.defineProperty
Can only hijack the properties of an object, whileProxy
Is a direct proxy object
Due to theObject.defineProperty
You can only hijack attributes and need to traverse every attribute of the object. whileProxy
You can proxy objects directly.Object.defineProperty
New attributes need to be manually addedObserve
Because ofObject.defineProperty
The object attributes are hijacked. Therefore, when adding attributes, you need to iterate over the object and reuse the new attributesObject.defineProperty
To hijack. It is also for this reason that the use of Vue todata
This parameter is required when an array or object is addedvm.$set
In order to ensure that the new properties are also responsive.Proxy
Support for 13 interception operations, this isdefineProperty
That you don’t have.- New standard performance bonus
Proxy
As a new standard, JS engines will continue to be optimized in the long runProxy
, butgetter
和setter
There will be very little targeted optimization. Proxy
Poor compatibility currently does not have a full supportProxy
Polyfill schemes for all intercepting methods
For a more detailed comparison, see my article why Did Vue3.0 no longer use defineProperty for data listening?
3. How to detect array changes in Vue?
Vue’s Observer handles the array separately, compiling the array’s methods and assigning them to the __proto__ attribute of the array property. Because of the prototype chain mechanism, finding the corresponding method does not continue to look up. Methods that add indexes (push, unshift, splice) are observed manually in the compiled method. Also refer to my article why Did Vue3.0 no longer use defineProperty for data listening? , there are detailed source code analysis.
4. Why is the data of the component written in functional form?
Vue components are reusable. After a component is created, it can be reused in multiple places. However, no matter how many times it is reused, the data in the component should be isolated from each other and not affected by each other. Changes to the data of each reusable component should not affect the data of other reusable components. To achieve this effect, data cannot be a pure object, but is in the form of a function return value, so each component instance can maintain a separate copy of the data without affecting each other.
5. What does nextTick do and how does it work?
The prerequisite for answering this question is to understand the EventLoop process. A deferred callback is performed at the end of the next DOM update loop, and nextTick is used to retrieve the updated DOM immediately after the data is modified. The macro task implementation, however, does not support Promise, and then points directly to the Macro task. The Macro task implementation, however, does not support setImmediate (advanced VERSIONS of IE and Etage support). If not, check whether MessageChannel is supported. If not, setTimeout 0 will be degraded. By default, micro Tasks are executed first, because micro tasks can be executed in a single tick, which has better performance in some scenes with redrawing and animation. However, due to the high priority of micro Task, in some cases, it can be triggered during event bubbling, causing some problems (see Vue for this issue: github.com/vuejs/vue/i…). Macro Task is mandatory in some places (e.g. V-on).
Note: To ensure that nextTcik is executed multiple times in the same tick, multiple asynchronous tasks are not started. Instead, these asynchronous tasks are compressed into a synchronous task. The execution is complete in the next tick.
6. Vue template compilation principle
The vUE template compilation process is divided into three stages:
- Step 1: Parse Parses the template string to generate an AST. The generated AST element node has three types: 1 is a normal element, 2 is an expression, and 3 is plain text.
- Step 2: Optimize syntax tree Not all data in the Vue template are responsive, and many data will never change after the first rendering, so the DOM generated by this part of data will not change, so we can skip the comparison of them in the process of patch.
In this stage, the generated AST tree will be deeply traversed to detect whether each of its sub-trees is a static node. If it is a static node, they will never need to change the DOM generation, which will greatly optimize the update of the template at runtime.
- The generated code
const code = generate(ast, options)
Copy the code
The AST generates the render function using the generate method. Babel, Vue compilation, Prettier, etc. I learned AST, where I no longer worry about being asked when Babel, Vue compilation, Prettier, etc.
7. What is the function of key in V-for?
Clear answer to this question, need to clear the Vue diff process, an article about the diff principle, recommend my.oschina.net/u/3060934/b…
Key is the unique ID assigned to each Vnode. In the process of vnode diff at the same level, you can quickly compare keys to determine whether they are the same node, and use the uniqueness of keys to generate a map to obtain corresponding nodes more quickly. In addition, when the key is specified, the “reuse in place” strategy is no longer used to ensure the accuracy of rendering.
8. Why are v-for and V-if not recommended together
When v-for and V-IF are on the same node, V-for has a higher priority than V-if, which means that V-IF will run separately in each V-for loop. This can be a significant performance waste if the array to be traversed is large and the actual data to be displayed is small. In this scenario, it is recommended to use computed data filtering first.
Routing related Issues
1. Vue-router What are the navigation guards
Global prefixes/hooks: beforeEach, beforeResolve, afterEach
Exclusive guard for routing: beforeEnter
Guards within components: beforeRouteEnter, beforeRouteUpdate, beforeRouteLeave
The complete navigation parsing flow is as follows:
- Navigation is triggered.
- Call the leave guard in the inactivated component.
- Call the global beforeEach guard.
- Call the beforeRouteUpdate guard (2.2+) in the reused component.
- Call beforeEnter in routing configuration.
- Parse the asynchronous routing component.
- Call beforeRouteEnter in the activated component.
- Call the global beforeResolve guard (2.5+).
- Navigation confirmed.
- Call the global afterEach hook.
- Trigger a DOM update.
- Call the callback passed to Next in the beforeRouteEnter guard with the created instance.
2. What is the difference between vue-router hash mode and history mode?
The difference between:
- Url display, hash mode has “#”, history mode does not
- When the page is refreshed, the hash mode is normally loaded to the page corresponding to the hash value, but if history is not processed, 404 is returned. Generally, all pages need to be configured to redirect to the home page route.
- Compatibility. Hash supports older browsers and Internet Explorer.
3. How are the vue-router hash mode and history mode implemented?
Hash mode: Changes in the hash value after # will not cause the browser to make a request to the server, and the browser will not refresh the page without making a request. You can also listen for the Hashchange event to see what changes have taken place in the hash, and then update parts of the page based on the hash changes.
History mode: The implementation of history mode is mainly the HTML5 standard published two apis, pushState and replaceState, which can change the URL, but do not send a request. This allows you to listen for URL changes to update parts of the page.
For the vue-Router section, the recommended article is juejin.cn/post/684490…
This article is the first in a series of articles titled “2020 Interview Guide for Big factories”. Please follow my official account “Front-end Xiaoyuan”. If you have any questions, please add my personal wechat yu_shihu_ to communicate