8 high frequency interview questions and answers of Vue

Time:2020-3-6

8 high frequency interview questions and answers of Vue

Preface

This paper introduces 8 high frequency interview questions and answers of Vue.

Review the front-end interview knowledge, is to consolidate the front-end basic knowledge, the most important or the usual accumulation!

Be careful: the questions of the article are separated by underscores. The answers are for reference only.

The full version of the front-end hardcore interview topic is here: the front-end hardcore interview topic, including: HTML + CSS + JS + ES6 + webpack + Vue + react + node + HTTPS + data structure and algorithm + GIT.

Vue

Understanding of MVC, MVP and MVVM

MVC mode means that the software can be divided into three parts.

8 high frequency interview questions and answers of Vue

  • View: user interface.
  • Controller: business logic.
  • Model: data saving.

The communication between the parts is as follows.

8 high frequency interview questions and answers of Vue

  • View transfers instructions to controller
  • After the controller completes the business logic, it requires the model to change the state
  • Model sends new data to view and users get feedback
  • All communications are one-way (counter clockwise).

MVP mode changes the name of controller to presenter and changes the direction of communication.

8 high frequency interview questions and answers of Vue

  • The communication between the parts is bidirectional (clockwise).
  • The view does not contact the model, but is passed through the presenter.
  • View is very thin and does not deploy any business logic. It is called “passive view”, that is, there is no initiative, and presenter is very thick. All logic is deployed there.

MVVM mode changes the name of presenter to ViewModel, which is basically the same as MVP mode.

8 high frequency interview questions and answers of Vue

The only difference is that it uses data binding: view changes are automatically reflected in the ViewModel, and vice versa. Both angular and ember use this mode.


How to understand that Vue performs DOM updates asynchronously?

  • Vue performs DOM updates asynchronously.
  • Whenever data changes are observed, Vue opens a queue and buffers 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 de duplication in buffering is important to avoid unnecessary computation and DOM manipulation.
  • Then, in the next event looptickIn, Vue refreshes the queue and performs the actual (de duplicated) work. Vue internally tries to use native promise.then and messagechannel for asynchronous queues. If the execution environment does not support it, it will use setTimeout (FN, 0) instead.

For example, when you set vm.somedata = ‘new value’, the component does not re render immediately.

  • When the queue is refreshed, the component will take the next step when the event loop queue is clearedtickTo update.
  • Most of the time we don’t need to worry about this process, but it can be tricky if you want to do something after the DOM state is updated.
  • While vue.js generally encourages developers to think in a “Data-Driven” way and avoid direct contact with the DOM, sometimes we do. To wait for Vue to finish updating DOM after data change, you can use vue.nexttick (callback) immediately after data change. In this way, the callback function will be called after the DOM update is completed.

Deep response principle

How to track changes

  • When you pass a normal JavaScript object to the data option of the Vue instance, Vue will traverse all the properties of the object and use object.defineproperty to transfer all the properties to getter / setter.
  • Object.defineproperty is a feature of Es5 that cannot be shimed, which is why Vue does not support IE8 and earlier browsers.
  • These getters / setters are invisible to users, but internally they let Vue track dependencies and notify changes when properties are accessed and modified. The problem to be noted here is that the format of getter / setter is not the same when the browser console prints data objects, so you may need to install Vue devtools to get a more friendly check interface.
  • Each component instance has a corresponding watcher instance object, which records the property as a dependency during component rendering. Then when the setter of the dependency is called, the Watcher will be notified to recalculate, so that its associated components can be updated.
  • The observer subscribes to the observable object. When the observable object publishes an event, the behavior of the observer is directly scheduled. Therefore, there is a dependency relationship between the observer and the observable object.

8 high frequency interview questions and answers of Vue


How to understand the virtual DOM algorithm?

There are several steps:

  • 1. Use JavaScript object structure to represent the structure of DOM tree, then use this tree to build a real DOM tree and insert it into the document;
  • 2. When the state changes, reconstruct a new object tree, and then compare the new tree with the old tree to record the differences between the two trees;
  • 3. Apply the differences recorded in step 2 to the real DOM tree built in step 1, and the view is updated.

Virtual DOM is essentially a cache between JS and DOM. It can be compared with CPU and hard disk. Since the hard disk is so slow, we will add a cache between them: since DOM is so slow, we will add a cache between JS and DOM. The CPU (JS) only operates the memory (virtual DOM), and writes the changes to the hard disk (DOM) at the last time.


Compare the differences between two virtual DOM trees

Comparing the differences between two DOM trees is the core part of the virtual DOM algorithm, which is also called the diff of virtual dom
Algorithm.
The complete diff algorithm of two trees is a problem with O (n ^ 3) time complexity. But in the front end, you rarely move DOM elements across levels.

So virtual DOM only compares elements at the same level:

8 high frequency interview questions and answers of Vue

The above divs will only be compared with those of the same level, and those of the second level will only be compared with those of the second level. In this way, the complexity of the algorithm can reach o (n).

Depth first traversal, record differences

In the actual code, the new and old trees will be traversed in depth first, so that each node will have a unique mark:

8 high frequency interview questions and answers of Vue

In depth first traversal, each node traversed is compared with the new tree. If there are differences, they will be recorded in an object.

The virtual DOM algorithm mainly implements the three functions of the above steps: element, diff, and patch. Then it can be used in practice:

//1. Build virtual DOM
var tree = el('div', {'id': 'container'}, [
    el('h1', {style: 'color: blue'}, ['simple virtal dom']),
    el('p', ['Hello, virtual-dom']),
    el('ul', [el('li')])
])
//2. Build real DOM through virtual DOM
var root = tree.render()
document.body.appendChild(root)
//3. Generate a new virtual DOM
var newTree = el('div', {'id': 'container'}, [
    el('h1', {style: 'color: red'}, ['simple virtal dom']),
    el('p', ['Hello, virtual-dom']),
    el('ul', [el('li'), el('li')])
])
//4. Compare the differences between two virtual DOM trees
var patches = diff(tree, newTree)
//5. Apply changes to real DOM elements
patch(root, patches)

Of course, this is a very rough practice. In practice, event monitoring needs to be handled. When generating virtual DOM, you can also add JSX syntax. If all these things are done, you can construct a simple react JS.


How do non parent-child components communicate?

Vue official website introduces the communication method of non parent-child components:

8 high frequency interview questions and answers of Vue

Write the following information in bus.js

import Vue from 'vue'
export default new Vue();

Introduce bus.js to all components requiring communication

<template>
  <div id="emit">
    < button @ Click = "bus" > button < / button >
  </div> 
</template > 
import Bus from './bus.js'
export default {
  data() {
    return {
      message: ''
    }
  },
  methods: {
    bus() {
      Bus. $emit ('msg ','I'm going to pass it to brother components, have you received it')
    }
  }
}

Listen for MSG events in the hook function:

<template>
    <div id="on">
      <p>{{message}}</p>
    </div>
</template>
import Bus from './bus.js'
export default {
    data() {
      return {
        message:  ''
      }
    },
    mounted() {   
       let self = this
       Bus.$on('msg', (e) => {
         self.message = e
         Console. Log (` the data is ${e} '))
       })
    }
 }

Finally P displays the message from $emit.


When should I use vuex?

  • While vuex can help us manage shared state, it comes with more concepts and frameworks. This requires a trade-off between short-term and long-term benefits.
  • If you don’t plan to develop large single page applications, using vuex can be cumbersome and redundant. Indeed, if your application is simple enough, you’d better not use vuex. A simple global event bus is enough for you.
  • However, if you need to build a large and medium-sized single page application, you are likely to consider how to better manage the state outside the component, and vuex will become a natural choice.

Vue process diagram

Diagram of Vue life cycle process

8 high frequency interview questions and answers of Vue

Vue responsive principle

8 high frequency interview questions and answers of Vue

Vue process diagram

8 high frequency interview questions and answers of Vue

Vuex

8 high frequency interview questions and answers of Vue

Vue classic interview related articles

  • 1. Understanding of source code and architecture of Vue, Vue router and vuex
  • 2. Vue life cycle
  • 3. Detailed explanation of Vue life cycle
  • 4. Six ways of communication between Vue components (complete version)
  • 5. Vue learning notes – implement a paging component

Last

The full version of the front-end hardcore interview topic is here: the front-end hardcore interview topic, including: HTML + CSS + JS + ES6 + webpack + Vue + react + node + HTTPS + data structure and algorithm + GIT.

If you think this article is not bad, please give a star. Your star is the driving force for me to keep updating!.

8 high frequency interview questions and answers of Vue