Perception: 🌟🌟🌟🌟🌟

Taste: Braised pig’s trotters

Cooking time: 15 minutes


This article is available on Github github.com/Geekhyt.

I could tell from the thickness of the lenses and the yellow and black plaid shirt that I was sitting in front of a bad interviewer. As usual, I’m going to take three minutes to introduce myself. In the meantime, TO avoid embarrassment, I stared into the middle of the eyebrows of the interviewer, who was clearly not very interested in my experience. He interrupted me at a minute and a half.

What technology stack do you think you’re best at?

Vue, I like you very much, recently released Vue’s first documentary, really good.

0. Can you tell me something about MVVM?

MVVM is short for Model-View-ViewModel, which is to evolve the Controller in MVC into ViewModel. The Model layer represents the data Model and the View represents the UI component. The ViewModel is the bridge between the View and the Model layer. The data is bound to the ViewModel layer and automatically renders the data to the page.

1. Briefly explain the principle of vue 2.x responsive data

When Vue initializes the data, it redefines all the properties in the data using object.defineProperty. When the page uses the corresponding properties, it first collects the dependencies (collects watcher for the current component) and notifies the dependencies if the properties change (publish subscribe).

2. Do you know how Vue3. X responds to data?

(Fortunately, I did. It doesn’t bother me.)

Use Proxy instead of Object. DefineProperty in Vue3. Because Proxy can directly listen for changes in objects and arrays, there are up to 13 intercepting methods. And as a new standard, browser vendors will continue to focus on performance optimization.

Proxy can only Proxy the first layer of an object, so how does Vue3 handle this?

(Easy.)

If the return value of reflect. get is an Object, and if it is an Object, make a proxy by using the reactive method, thus realizing the depth observation.

It’s possible to get/set multiple times while monitoring an array, so how do you prevent this from happening multiple times?

We can determine whether the key is a property of the target itself, or whether the old value is equal to the new value. The trigger can be executed only if one of the above two conditions is met.

The interviewer looked up. You think

(This guy is ok, better than the last two, should be more or less seen Vue3 source code)

3. Again, how to monitor array changes in vue2.x

Using the method of function hijacking, Vue overrides the array method. Vue overrides the array in the data prototype chain, pointing to the array prototype method defined by himself. This allows you to notify dependency updates when the array API is called. If the array contains reference types, the recursion through the array of reference types is monitored. This implements the monitoring of array changes.

(Interviewers who ask this tend to focus on depth, so keep these routines in mind.)

(Details on the prototype chain can be found in another column of mine.)

This article takes you through the JavaScript prototype chain

Do you know how to implement nextTick?

The deferred callback is performed after the next DOM update loop ends. NextTick mainly uses macro tasks and microtasks. Try each one according to the execution environment

  • Promise
  • MutationObserver
  • setImmediate
  • If all else fails, use setTimeout

Defines an asynchronous method that clears the current queue by calling nextTick multiple times to store the method in the queue.

(See my other two columns about macro and microtasks and event loops.)

(As you can see from this, frameworks are ultimately a test of your native JavaScript skills.)

JavaScript event loops in the browser

Node.js event loop

5. Talk about the lifecycle of Vue

BeforeCreate is the first hook that is triggered after new Vue(). Data and methods on Data, Methods, computed, and Watch are not accessible at this stage.

So created happens after the instance is created, so now you’re done observing the data, so you can use the data, you can change the data, and in this case changing the data doesn’t trigger an updated function. You can do some initial data fetching, you can’t interact with the Dom at this stage, and if you want, you can access the Dom via vm.$nextTick.

BeforeMount occurs before the mount, before the template template is compiled with the imported rendering function. 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 point without triggering an updated.

Mounted occurs after the mounting is complete. In the current stage, real Dom is mounted, data is bi-directional bound, and Dom nodes can be accessed and Dom operations can be performed using the $refs attribute.

BeforeUpdate is triggered before the responsive data is updated and the virtual DOM is rerendered. You can change the data in the current phase without causing rerendering.

Updated occurs after the update is complete. The Dom of the component in the current phase has been updated. It is important to avoid changing the data during this period, as this may result in an infinite loop of updates.

BeforeDestroy happens before the instance is destroyed, when the instance is fully available in the current phase and we can clean up the mess such as cleaning the timer.

Destroyed occurs after the instance is destroyed, leaving only the DOM shell. The component has been disassembled, the data binding removed, the listener removed, and the child instance destroyed.

(For a detailed explanation of Vue’s lifecycle, please refer to another of my columns.)

Read the Vue lifecycle from the source code, let the interviewer sit up and take notice of you

6. In which lifecycle do your interface requests typically fall?

Mounted is not supported for server rendering, so it should be placed in created.

7. Talk about Computed and Watch

Computed is essentially a watcher with a cache that updates the view when dependent properties change. This method applies to computing scenarios where performance is consumed. When the expression is too complex, putting too much logic in the template will make the template difficult to maintain, and the complex logic can be handled in evaluated properties.

Watch has no caching function and is more of an observation function. It can listen to certain data and perform callback. When we want to deeply listen for properties in an object, we can turn on the deep: true option, which will listen for every item in the object. This can cause performance problems, so you can listen as a string for optimization, and don’t forget to log out manually with unWatch if it’s not written to a component.

What’s the difference between a V-if and a V-show

V-if does not render the DOM element when the condition is not established, and V-show operates on the style (display), switching the current DOM display and hide.

9. Why is data in a component a function?

When a component is reused multiple times, multiple instances are created. Essentially, these instances use the same constructor. If data is an object, the object is a reference type and affects all instances. So to ensure that data does not conflict between different instances of a component, data must be a function.

10. How does the V-Model work

V-model is essentially a syntactic sugar, and you can think of it as the syntactic sugar of the Value + input method. You can customize this using the Prop and Event properties of the Model property. The native V-Model generates different events and attributes depending on the tag.

11.Vue event binding principle

Native event bindings are bound to real elements through addEventListener, and component event bindings are implemented through Vue’s custom $ON.

Interviewer :(this kid’s basic is ok, next I have to go up the difficulty)

12. Do you know the compiling principle of Vue template? Could you briefly explain it?

In simple terms, the Vue compile process is to convert the template to the render function. Will go through the following stages:

  • Generate the AST tree
  • To optimize the
  • codegen

The template is first parsed to generate an AST syntax tree (a form of JavaScript object that describes the entire template). Use a large number of regular expressions to parse the template, encountered tags, text will execute the corresponding hook processing.

Vue’s data is responsive, but not all data in the template is responsive. Some data will not change after the first rendering, and the CORRESPONDING DOM will not change. So the optimization process is to traverse the AST tree in depth and mark the tree nodes according to relevant conditions. With these tagged nodes (static nodes), we can skip comparing them and greatly optimize the runtime template.

The final step of compilation is to convert the optimized AST tree into executable code.

Interviewer :(young spirit ah, something, the difficulty is increased, do not believe that you can’t beat)

13. Describe the diff algorithm of vue2.x and VUe3.x renderer respectively

In short, the diff algorithm has the following procedure

  • Peer comparisons, and then child comparisons
  • (if the new children have no children, remove the old children) (if the new children have no children)
  • Compare the case where both have child nodes (core DIff)
  • Recursively compare the child nodes

In normal Diff, the time complexity of the two trees is O(n^3), but in reality, we rarely move DOM across hierarchies, so Vue optimized Diff from O(n^3) -> O(n). Only when both old and new children have multiple child nodes, the core Diff algorithm needs to be used to compare the same hierarchy.

The core Diff algorithm of Vue2 adopts the algorithm of double-end comparison. At the same time, the comparison starts from the two ends of the old and new children, and the reusable nodes are found with the help of key values, and then relevant operations are carried out. Compared with React Diff algorithm, it can reduce the number of mobile nodes in the same case, reduce unnecessary performance loss, and is more elegant.

Vue3. X borrows from ivI and Inferno

The type of VNode is determined when it is created, and the type of a VNode is determined by bit operation during the process of mount/patch. On this basis, the core Diff algorithm is combined with the core Diff algorithm to improve the performance compared with ve2. (The actual implementation can be seen in conjunction with the Vue3. X source code.)

The algorithm also uses the idea of dynamic programming to solve the longest recursive subsequence.

(As you can see, there are data structures and algorithms everywhere in the framework.)

Interviewer :(ok, ok, it seems to be a seedling, but the self-introduction is true some boring, next question)

(Do not 6)

14. Tell me more about the virtual Dom and the role of the key attribute

Because manipulating the DOM in the browser is expensive. Frequent manipulation of the DOM can cause performance problems. This is where the virtual Dom comes in.

The Virtual DOM of Vue2 draws lessons from the implementation of snABbDOM, an open source library.

The essence of a Virtual DOM is to use a native JS object to describe a DOM node. Is a layer of abstraction from the real DOM. (This is the VNode class in the source code, which is defined in SRC /core/vdom/vnode.js.)

The mapping from VirtualDOM to the real DOM goes through the create, diff, and patch phases of the VNode.

The purpose of the key is to reuse as many DOM elements as possible.

Only when the order of the nodes in the old and new children is different, the best operation is to move the element to achieve the update.

You need to save the mapping between the nodes of the old and new children so that you can find the reusable nodes in the nodes of the old children. Key is the unique identifier of the node in children.

15. Keep alive – understand

Keep-alive caches components without uninstalling the current component when the component is switched.

Two common attributes, include/exclude, allow components to conditionally cache.

Two life cycles, activated and deactivated, are used to determine whether the current component is active.

Keep-alive also uses LRU(Least Recently Used) algorithm.

(Data structure and algorithm again, the original algorithm also has so many applications in the front end)

16. Component lifecycle call sequence in Vue

Components are called in the order of first parent and then child, and rendered in the order of child and then parent.

The destruction of components is done in the order of first child and then parent.

Loading the render process

Parent beforeCreate-> parent created-> parent beforeMount-> child beforeCreate-> child created-> child beforeMount-> Child Mounted -> parent

Child component update process

Parent beforeUpdate-> child beforeUpdate-> child updated-> parent updated

Parent component update process

Parent beforeUpdate -> Parent updated

Destruction of the process

Parent beforeDestroy-> child beforeDestroy-> child Destroyed -> parent Destroyed

17. What are the communication modes of the Vue2.x component?

  • Parent-child communication

    $on, $emit, $emit

    Get the parent component instances $parent, $children

    Ref gets an instance by calling a component property or method

    Provide and inject are not recommended officially, but are commonly used when writing component libraries

  • Sibling communication

    Prototype.$Bus = new Vue

    Vuex

  • Cross-level component communication

    Vuex

    $attrs, $listeners

    Dojo.provide, inject

18. Do you know SSR?

SSR is also called server rendering, which means that Vue renders the tags to HTML on the client side and then returns the HTML directly to the client side.

SSR has the advantages of better SEO and faster first screen loading. However, it also has some disadvantages, such as our development conditions are limited, server rendering only supports beforeCreate and Created hooks, we need special treatment when we need some external extension library, server rendering application also needs to be in the node.js runtime environment. There will also be a greater load on the server.

19. What Vue performance optimizations have you done?

Coding phase

  • Minimize the amount of data in data, getters and setters will be added to the data, and watcher will be collected
  • V-if and V-for cannot be used together
  • Use the event broker if you need to bind events to each element using V-for
  • The SPA page uses the keep-Alive cache component
  • In more cases, use v-if instead of V-show
  • The key is guaranteed to be unique
  • Use route lazy loading, asynchronous components
  • Anti-shaking, throttling
  • Import third-party modules as required
  • The long list is dynamically loaded by scrolling into the visible area
  • Lazy image loading

SEO optimization

  • pre-rendered
  • Server-side render SSR

Packaging optimization

  • The compression code
  • Tree Shaking/Scope Hoisting
  • The CDN is used to load the third-party module
  • Multithreading packages happypack
  • SplitChunks pulls the public file
  • SourceMap optimization

The user experience

  • Skeleton screen
  • PWA

You can also use caching (client caching, server caching) optimizations, enable GZIP compression on the server, and more.

(Optimization is a big project, involving many aspects, here apply for another column)

20. This section describes the implementation principles of hash and History routes

The value of location.hash is actually whatever comes after the # in the URL.

History is actually implemented using apis provided in HTML5, mainly history.pushState() and history.replacestate ().

The interviewer picked up the chilly coffee on the side and took a sip.

(Can’T I ask the kid?)

Keep updating…

❤️ love triple strike

1. When you see this, please click a “like” to support it. Your “like” is the motivation for my creation.

2. Pay attention to the public number front canteen, “your front canteen, remember to eat on time”!

3. github.com/Geekhyt, thanks Star.