Summarize the Vue related questions encountered in the interview, see the full versionA set of interview questions

1. What is the virtual Dom and why does it exist?

The Web interface is built from a DOM tree (a tree stands for data structure), and when one part of it changes, it actually changes a DOM node. The virtual DOM is designed to solve browser performance problems.

For example, if there are 10 DOM updates in one operation, the virtual DOM will not immediately manipulate the DOM, but save the diff content of the 10 updates to a local JS object, and finally attch the JS object to the DOM tree for subsequent operations to avoid a lot of unnecessary calculation.

Therefore, the advantage of using JS object to simulate DOM node is that the update of the page can be reflected in THE JS object (virtual DOM), and the speed of the JS object operation in memory is obviously faster. After the completion of the update, the final JS object is mapped into the real DOM and submitted to the browser to draw.

But when some special requirements (such as the need to delete the table element (1000) in all of the data and then increase), after this common dom only need to delete all increase, virtual dom need a lot more, but we can’t foresee how data changes, in the most extreme cases, Vdom efficiency is relatively high.

2. Talk about the Diff algorithm

The Diff algorithm is used to figure out what part of the Virtual DOM is changed, and then perform native DOM operations on that part without having to re-render the entire page. Diff algorithm has three strategies:

  • Tree Diff
  • Component Diff
  • Element Diff

The execution sequence of the three policies is also the same. Tree Diff is to walk through each layer of a Tree and find out the differences.

Component Diff is a data-level difference comparison

  • If both are components of the same type (i.e., two nodes are two different instances of the same component class, for example:<div id="before"></div>with<div id="after"></div>), continue to compare the Virtual DOM tree according to the original policy
  • If a component is not of the same type, it is judged to be a dirty component and all child nodes under the entire component are replaced

Element Diff real DOM rendering, structure differences comparison

When nodes are at the same level, Diff provides three DOM operations: delete, move, and insert.

The beginning and end positions of OldVnode and NewVnode were marked as oldS, oldE, newS and newE respectively to optimize the comparison process.

3. What are the important concepts of Vuex

Vuex core concepts: State, getter, mutation, Action, module

  • State: state, mapstate can be used in the page to simplify calls
  • Getter: Analogous to computed properties in VUE, the return value of a getter is cached according to its dependencies and recalculated only when its dependencies change. Here we can get it by defining the getter of vuex, and Getters can be used to listen for changes in values in, and state. Returns the calculated result,
  • Muation: Modifies the value in state
  • Action: The biggest benefit of mutation is that the request can be dispatched asynchronously
  • Module: Separates large modules

4. Basic principles of Vuex

The basic Vue state self-management application consists of the following parts:

  • State, the data source that drives the application;
  • View, to declaratively map state to the view;
  • Actions, in response to changes in state caused by user input on the view.

However, the simplicity of one-way data flow can easily be broken when our application encounters multiple component shared state:

  • Multiple views depend on the same state.
  • Actions from different views need to change the same state.

So why don’t we extract the shared state of the components and manage it in a global singleton? In this mode, our tree of components forms a giant “view” where any component can get state or trigger behavior no matter where it is in the tree!

Implementation principle: Vuex uses the mixin mixing mechanism of vue to mix vuexInit method before beforeCreate hook. VuexInit method realizes store injection vUE component instance, and registers vuex Store reference attribute $store. The store injection process is shown below:

5. Bidirectional binding principle of Vue

MVVM data bidirectional binding, that is, data changes update view, view changes update data.

Update data for views

  • You can use event listening, for exampleV-on (for binding HTML events);V-bind (for setting HTML attributes);V-on (for binding HTML events);V-model: Create bidirectional data binding on form control elements:
  • Native listener events – onInput,onclick,hover… addeventlistener

For data update view

  • Each read and write of the data can be seen by us, that is, we can know when the data is read or when the data has been rewritten, which we call the “observable” of the data change;

– 1. Vue2.0: Object. DefineProperty () method directly on an Object to define a new attribute, or modify existing attribute of an Object, and returns the Object.

– 2. Vue3.0: proxy ()

  • Once the data is’ observable ‘, we can notify views that depend on it of updates when the data is read or written. For convenience, we need to collect all dependencies first and notify them of updates as soon as the data changes. In essence, this is a typical “publish subscriber” pattern, where the data is changed to “publisher” and the dependency object is “subscriber”.

6. How to implement redo and undo operations

New pushState() and replaceState() methods in HTML5 History Interface. (Browser-specific support required) These two methods apply to the browser’s history stack and provide the ability to modify the history in addition to the existing back, Forward, and Go methods. It’s just that when they make changes that change the current URL, the browser doesn’t immediately send requests to the back end. Vue-router utilizes both of these features to implement front-end routing by calling the interface provided by the browser.

7. Data transfer of parent and child components

Parent component to child component:

  • The child component creates a property in props to receive the value passed by the parent component
  • Register child components in parent components
  • Add the properties created in the child component props to the child component tag
  • Assign the value that needs to be passed to the child component to this property
// Parent food.vue <template> <apple :type="type"></apple> </template> <script> data (){return {type: 0}; {{childType}}</span> </span> </template> <script> <script> ['type'], created () { this.childType = this.formatterType(type); }, method () {formatterType (type) {if (type === 0) {return "0 fruit "; } if (type === 1) {return "1 "; } return ''; } } </script>Copy the code

Child component passes value to parent:

  • The child component needs to fire a custom event in some way, such as a click event method
  • The value that you want to pass as the second argument to $emit will be passed as an argument to the method that responds to the custom event
  • Registers the child component in the parent component and binds listeners to custom events on the child component label

How to understand componentization

<! -- Parent --> <template> <div class="test"> < test-com@childfn ="parentFn"></test-com> <br/> {{message}} </div> </template> <script> export default { // ... data: { message: '' }, methods: { parentFn(payload) { this.message = payload; } } } </script> <! <template> <div class="testCom"> <input type="text" v-model="message" />  </div> </template> <script> export default { // ... Data () {return {// default message: 'I am a message from a child'}}, methods: {click() {this.$emit('childFn', this.message); } } } </script>Copy the code

8. If you were asked to write a component, what would you notice?

  • Improve development efficiency
  • Easy to reuse
  • Simplify debugging steps
  • Improve the maintainability of the entire project
  • Facilitate collaborative development

9.Vue lifecycle

Vue has eight life stages: before, after, load, load, update, update, destroy, and destroy, each of which corresponds to a lifecycle hook function.

(1) beforeCreate hook function, after instance initialization, before data listening and event configuration. So we don’t get data in this event.

(2) Created hook function, which is triggered when the instance is created and can access properties such as data and methods. However, the component is not yet mounted to the page, so the $EL property is not accessible at this time. This function usually does some page initialization, such as making an Ajax request for data to initialize the page.

BeforeMount hook function, triggered before component is mounted to the page. Before beforeMount, the corresponding template is found and compiled into the render function.

The mounted hook function is triggered after the component is mounted to the page. At this point, DOM elements in the page can be retrieved through the DOM API.

BeforeUpdate hook functions are triggered during reactive data updates, before the virtual DOM is re-rendered and patched, at which time we can do some actions on elements that may be removed, such as removing event listeners.

Updated hook function, invoked after virtual DOM is re-rendered and patched.

BeforeDestroy hook function, called before instance destruction. In this step we can destroy timers, unbind global events, and so on.

Everything in the Vue instance is unbound, all event listeners are removed, and all subinstances are destroyed after the instance is destroyed.

When we use keep-alive, there are also two hook functions, activated and deactivated. Components wrapped with keep-alive are not destroyed during switching, but cached in memory and executed by deactivated hook function. After hitting the cache rendering, the actived hook function is executed.

10.MVC/MVP/MVVM difference?

MVC, MVP and MVVM are three common software architecture design patterns, which mainly organize code structure by separating concerns and optimize our development efficiency.

MVC organizes code structure by separating Model, View, and Controller. View is responsible for the display logic of the page, Model is responsible for storing the business data of the page, and the operation of the corresponding data. And the View and Model apply observer mode, which notifies the relevant View layer to update the page when the Model layer changes. The Controller layer is the link between the View layer and the Model layer, and it is mainly responsible for the response operation of users and applications. When users interact with the page, the event trigger in Controller starts to work, and the Model is modified by calling the Model layer. The Model layer then notifies the View layer of updates.

The only difference between the MVP pattern and MVC is Presenter and Controller. In the MVC pattern, we use the observer pattern to notify the View layer of updates when the Model layer data changes. This coupling of the View layer and the Model layer can lead to confusing code when the project logic becomes complex, and can cause problems with code reusability. The MVP pattern uses Presenter to decouple the View layer from the Model layer. The Controller in MVC only knows the interface of the Model, so it has no way to control the update of the View layer. In MVP mode, The View layer’s interface is exposed to the Presenter so we can bind Model changes to View changes in the Presenter, so that the View and Model can be updated simultaneously. This decouples the View from the Model, and Presenter also includes other response logic.

The VM in MVVM mode refers to the ViewModel, which has the same idea as MVP, but automates simultaneous updates of View and Model through two-way data binding. When the Model changes, the ViewModel updates automatically; The ViewModel changes, the View updates. This automates the work in Presenter. I’ve seen a little bit about two-way data binding, such as vUE’s ability to do this by using data hijacking and publishing subscriber patterns.

11. Have you read the Vue source code?

12. com puted principle

1. Each computed attribute generates a corresponding observer (Watcher instance) with values attributes and GET methods. The getter function for a computed property is called in the GET method and assigns the returned value to value. Set the initial values of dirty and lazy to true, and lazy does not get methods immediately (lazy execution), but instead executes them when computed values are read. 🐷 underline, here’s how Vue avoids duplicate rendering

2. Add a computed property to the component instance, use get and set to get or set the property value, and redefine the getter function.

3. During the initial rendering of the page, computed property values are read and the redefined getter function is triggered. Since the observer’s dirty value is true, the get method is called, executing the original getter function. Data (reactive) data is read in the getter function, and data’s getter method is triggered when the data is read, adding the observer corresponding to the computed property to data’s dependent collector (used to notify of updates when data changes). After the observer’s get method is executed, the observer’s value is updated and dirty is set to false to indicate that the value is updated. After executing the Observer’s Depend method, the upper observer (this observer contains the page update method, Method that reads computed property values) is also added to the dependency collector of Data in the getter function. (The dependency collector of Data in the getter contains observers for computed, And the observer that contains the page update method (with a computed property invoked), and finally returns the value of the computed observer.

4. When you change the data value dependent on the computed property getter function, the update method of the observer is called sequentially, and the update method of the computed observer is called first, based on the observers collected by the previous dependency. Because lazy is true, The observer’s dirty is set to true, indicating that the data value that the computed property getter depends on has changed, but the observer’s GET method is not called to update the value. Then call the update method of the observer that contains the page update method. When the page is updated, the value of computed property is read and the redefined getter function is triggered. At this time, because the observer with computed property is dirty is true, call the get method of the observer. Update value and return to finish rendering the page.

5. Initialize the dirty value to true, that is, when a computed property value is first read, it is calculated according to the setter and stored on the observer value, and then set the dirty value to false. When a computed property value is later read, the dirty value is false, and instead of calling the setter to recalculate the value, the observer’s value, which was the last computed value, is returned directly. Set dirty to true only when the data on which the computed property setter function depends changes, that is, the setter is called to recalculate the next time a computed property value is read. That is, when data dependent on a computed property does not change, setter functions are not called to recalculate the value, but to read the last calculated value.

13. Why can’t muation have an asynchronous operation in VUex? If so, what can be done?

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.

Action: Can be asynchronous, but cannot operate State directly.

14. What other method does Vue use to set reactive data besides set?

Object addition properties can also be replaced with a new Object that is returned with object. assign({},obj1,obj2)

Using JavaScript’s array manipulation functions, each of these methods returns a new array, which is the principle of array substitution.

forceUpatde

15. Vue select tag optimization

16. How does vue get the real DOM

<div class='box' ref='myBox'> Hello </div> this.$refs.mybox. StyleCopy the code

17. Vue3 new features

17.1 Detection Mechanism

The observer implementation in VUe2 is based on object.defineProperty, and the observer implementation in VUe3 is based on Proxy

  • Monitor the addition and deletion of attributes
  • Subscription-based modification of arrays, forlengthModified monitoring
  • Map and Set support

The default is lazy monitoring

  • 1. In 2.x version, responsive data will be monitored at startup. If the data volume is large, it will have serious performance consumption
  • In 3.x, only the data used for the initial visible part of the application will be monitored

More accurate notification of changes:

  • 1. In the 2.x version, passVue.setForces a new attribute to be added to all dependencies on this objectwatchFunctions are executed once
  • 2. In 3.x, there are only those that depend on this concrete attributewatchFunction notified

Better debugging:

  • 1, by using the newrenderTrackedandrenderTriggeredHooks that track exactly when and why a component is rerendered

Expose the API of observables to create responsive objects, which can replace the Event Bus for cross-component communication

17.2 Performance Optimization

Component rendering:

  • In version 2.x, when the parent component is re-rendered, its children must also be re-rendered (if the modified data is the props of the child component).
  • 2. In version 3.x, you can re-render child or parent components separately

Static tree lifting

  • In 3.x, the compiler can detect static components and improve them, reducing rendering costs

Static attribute promotion

17.3 Composition API

18. What is a Vue Loader?

Vue Loader is a Webpack Loader that allows you to write Vue components in a format called single-file Components (SFCs) :

<template> <div class="example">{{ msg }}</div> </template> <script> export default { data () { return { msg: 'Hello world! ' } } } </script> <style> .example { color: red; } </style>Copy the code

The Vue Loader also provides a number of cool features:

  • Allow the use of other WebPack loaders for each part of the Vue component, such as Sass in the part and Pug in the part;
  • Allow custom blocks to be used in a.vue file and apply custom loader chains to them;
  • Use webPack Loader to treat resources referenced in and as module dependencies;
  • Scoped CSS is simulated for each component;
  • Use hot overloading to preserve state during development.

19. Vue created and Mounted

  • **created:** called before the template is rendered into HTML, which usually initializes some property values and then renders into a view.
  • ** Mounted: Specifies whether to perform any required operations on the HTML DOM node after the template has been rendered to HTML.

20. keep-alive

In our normal development, there’s always some component that we don’t need to Init multiple times, we need to persist the component so that the state of the component stays the same, and the next time we show it, we don’t need to Init keepalive again, So in VUE we can use Keepalive for basic use of component caching

<keep-alive> <component /> </keep-alive>Copy the code

Other operations and hooks

<keep-alive include=" A, B "> <component :is="currentView"/> </keep-alive> // Do not cache <keep-alive for c Exclude ="c"> <component :is="currentView"/> </keep-alive> // Exclude takes precedence over include, <keep-alive include="a,b" exclude="b"> <component :is="currentView"/> </keep-alive> // <keep-alive exclude="c" Max ="5"> <component :is="currentView"/> </keep-alive>Copy the code

21. Lifecycle of parent and child components

  • Loading the rendering process
Parent beforeCreate-> Parent created-> parent beforeMount-> child beforeCreate-> child created-> child beforeMount-> Child Mounted -> parent MountedCopy the code
  • Child component update process
Parent beforeUpdate-> Child beforeUpdate-> Child updated-> Parent updatedCopy the code
  • Parent component update process
Father father beforeUpdate - > updatedCopy the code
  • Destruction of the process
Parent beforeDestroy-> Child beforeDestroy-> Child destroyed-> Parent destroyedCopy the code