2021VUE Interview questions + answers

Vue video tutorial series:

Vue3+ElementPlus+Koa2 Full stack development background system

Video lessons: Click to watch

Full course catalog: Click here to view

Vue3.0 Advanced combat: Developing high-quality music Web app

Video lessons: Click to watch

Full course catalog: Click here to view

VUE comprehensive teaching +VUE open source project super combat:

Video lessons: Click to watch

Full course catalog: Click here to view

Vue3/VueJS technical Details

Video lessons: Click to watch

Full course catalog: Click here to view

Latest and most complete front-end project (small program +VUE+Noed+React+ UNI APP +Express+Mongodb)

Video lessons: Click to watch

Full course catalog: Click here to view

What’s the difference between V-show and V-IF?

V-if is true conditional rendering because it ensures that event listeners and subcomponents within the conditional block are properly destroyed and rebuilt during the switch; Also lazy: if the condition is false during the initial render, nothing is done — the conditional block does not start rendering until the condition is true for the first time.

V-show is much simpler — elements are always rendered regardless of initial conditions, and simply switch based on the “display” property of CSS.

Therefore, V-IF is suitable for scenarios where conditions are rarely changed at runtime and do not need to be switched frequently; V-show is suitable for scenarios that require very frequent switching of conditions.

What are the differences between computed and watch and the application scenarios?

Computed: Computed attributes depend on other attribute values, and computed values are cached. Only when the dependent attribute values change, computed values will be recalculated the next time it obtains computed values.

Watch: It is more of a function of “observation”, similar to the listening callback of some data. Whenever the monitored data changes, the callback will be executed for subsequent operations.

Application scenario:

  • When we need to do numerical calculations and rely on other data, we should use computed, because we can take advantage of the caching nature of computed and avoid recalculating each time we get a value.
  • Watch should be used when we need to perform asynchronous or expensive operations when data changes. Using the Watch option allows us to perform asynchronous operations (accessing an API), limits how often we perform that operation, and sets the intermediate state until we get the final result. These are all things you can’t do with computed properties.

How many ways can Vue components communicate

  1. The props and EMIT parent components pass data to the child components via prop, the child components pass data to the parent components via PROP, the child components pass data to the parent components via prop, and the emit parent components pass data to the child components via prop, The child component passes data to the parent component by emitting an event
  2. The parent, the parent, the parent and children takes the current components of the parent component and the current component child components
  3. Attrs and listeners A->B->C Vue 2.4 starts with attrs and attrs and attrs and Listeners to address this problem
  4. Variables are provided by provide in the parent component and injected by inject in the child component. (Officially not recommended for use in real business, but commonly used when writing component libraries)
  5. $refs gets the component instance
  6. The envetBus sibling can use the event bus approach for data transfer in this case
  7. Vuex status management

What are the lifecycle methods of Vue

BeforeCreate is called after instance initialization and before data Observer and Event/Watcher event configuration. In the current phase, data and methods on Data, methods, computed, and Watch cannot be accessed

Called after the created instance has been created. In this step, the instance completes the configuration of data Observer, property and method operations, and Watch/Event event callbacks. There’s no EL, so if you really want to interact with the Dom, you can use vm.el, if you really want to interact with the Dom, you can use vm.el, if you really want to interact with the Dom, you can access the Dom through vm.nextTick

BeforeMount is called before the mount begins: the associated render function is called for the first time.

Mounted Occurs after the Dom is mounted. In this stage, the REAL Dom is mounted, data is bound, and Dom nodes can be accessed

BeforeUpdate is called when data is updated and occurs before the virtual DOM is re-rendered and patched. You can further change the state in this hook without triggering additional rerendering

Updated occurs after the update is complete, and the component Dom is updated in the current phase. Care should be taken to avoid changing the data during this time, as this may result in an infinite loop of updates, and the hook is not called during server-side rendering.

BeforeDestroy Called before instance destruction. At this step, the instance is still fully available. This is where we can clean up the mess, like clearing timers.

Called after the Destroyed Vue instance is destroyed. When called, everything indicated by the Vue instance is unbound, all event listeners are removed, and all subinstances are destroyed. This hook is not called during server-side rendering.

Activated keep-alive Is used when the component is activated

Deactivated keep-alive Is exclusive and is invoked when a component is destroyed

At what stage is the asynchronous request initiated?

Asynchronous requests can be made in hook functions created, beforeMount, and Mounted because in these three hook functions data is already created and can be assigned to the data returned by the server.

If an asynchronous request does not need to rely on Dom, it is recommended to call an asynchronous request in a Created hook function, because calling an asynchronous request in a Created hook function has the following advantages:

  • The server data can be obtained faster, reducing page loading time.
  • SSR does not support beforeMount and Mounted hook functions, so creating helps consistency.

The responsivity principle of Vue3.0 and 2.0 is different

Vue3. X uses Proxy instead of Object.defineProperty. Because proxies can listen directly for changes in objects and arrays, there are as many as 13 interception methods.

The relevant codes are as follows

import { mutableHandlers } from "./baseHandlers"; // Proxy related logic
import { isObject } from "./util"; // Tool methods

export function reactive(target) {
  // Create different responsive objects according to different parameters
  return createReactiveObject(target, mutableHandlers);
}
function createReactiveObject(target, baseHandler) {
  if(! isObject(target)) {return target;
  }
  const observed = new Proxy(target, baseHandler);
  return observed;
}

const get = createGetter();
const set = createSetter();

function createGetter() {
  return function get(target, key, receiver) {
    // Radiate the obtained value
    const res = Reflect.get(target, key, receiver);
    console.log("Property acquisition", key);
    if (isObject(res)) {
      // If the value obtained is an object type, the proxy object for the current object is returned
      return reactive(res);
    }
    return res;
  };
}
function createSetter() {
  return function set(target, key, value, receiver) {
    const oldValue = target[key];
    const hadKey = hasOwn(target, key);
    const result = Reflect.set(target, key, value, receiver);
    if(! hadKey) {console.log("New Properties", key, value);
    } else if (hasChanged(value, oldValue)) {
      console.log("Property value modified", key, value);
    }
    return result;
  };
}
export const mutableHandlers = {
  get, // This method is called when an attribute is obtained
  set, // This method is called when properties are modified
};
Copy the code

The responsivity principle of Vue3.0 and 2.0 is different

Vue3. X uses Proxy instead of Object.defineProperty. Because proxies can listen directly for changes in objects and arrays, there are as many as 13 interception methods.

The relevant codes are as follows

import { mutableHandlers } from "./baseHandlers"; // Proxy related logic
import { isObject } from "./util"; // Tool methods

export function reactive(target) {
  // Create different responsive objects according to different parameters
  return createReactiveObject(target, mutableHandlers);
}
function createReactiveObject(target, baseHandler) {
  if(! isObject(target)) {return target;
  }
  const observed = new Proxy(target, baseHandler);
  return observed;
}

const get = createGetter();
const set = createSetter();

function createGetter() {
  return function get(target, key, receiver) {
    // Radiate the obtained value
    const res = Reflect.get(target, key, receiver);
    console.log("Property acquisition", key);
    if (isObject(res)) {
      // If the value obtained is an object type, the proxy object for the current object is returned
      return reactive(res);
    }
    return res;
  };
}
function createSetter() {
  return function set(target, key, value, receiver) {
    const oldValue = target[key];
    const hadKey = hasOwn(target, key);
    const result = Reflect.set(target, key, value, receiver);
    if(! hadKey) {console.log("New Properties", key, value);
    } else if (hasChanged(value, oldValue)) {
      console.log("Property value modified", key, value);
    }
    return result;
  };
}
export const mutableHandlers = {
  get, // This method is called when an attribute is obtained
  set, // This method is called when properties are modified
};
Copy the code

Why is Proxy adopted in Vue3.0 and Object. DefineProperty abandoned?

Object.defineproperty itself has some ability to detect array subscript changes, but in Vue, this feature is deprecated for performance/experience value reasons. To solve this problem, after internal vUE processing, you can use the following methods to listen on arrays

push(); pop(); shift(); unshift(); splice(); sort(); reverse(); Copy the codeCopy the code

Because only the above 7 methods are hacked, other array attributes can not be detected, or there are certain limitations.

Object.defineproperty can only hijack attributes of objects, so we need to traverse each attribute of each Object. In Vue 2.x, the monitoring of data is achieved by recursion + traversal of the data object. If the attribute value is also an object, it needs deep traversal. Obviously, hijacking a complete object is a better choice.

A Proxy can hijack an entire object and return a new object. Proxy can Proxy not only objects, but also arrays. You can also proxy dynamically added properties.

The implementation principle of computed

Computed in nature is an lazily evaluated observer.

Computed implements an inert WATcher internally, that is,computed Watcher, which does not evaluate immediately and holds an instance of DEP.

The this.dirty attribute tag internally calculates whether the attribute needs to be reevaluated.

When computed dependency status changes, the lazy Watcher is notified,

Computed Watcher detects subscribers by this.dep.subs.length,

If it does, it recalculates and compares the old and new values, and if it changes, it rerenders. (Vue wanted to make sure that not only did the values of the calculated property dependencies change, but that the rendering Watcher was only triggered to re-render when the final calculated value of the calculated property changed, essentially an optimization.)

If not, just set this.dirty = true. (When a calculated property depends on other data, it is not recalculated immediately, but only computed later when the property needs to be read elsewhere, which is called lazy.)

What exactly does a key in Vue do?

The key is the unique ID given to each vNode, with which our diff operations can be more accurate and faster (diff nodes are also faster for simple list page rendering, but with hidden side effects such as not having transitions, or binding data (form) state on some nodes, State mismatches can occur.)

In the process of diFF algorithm, the beginning and end of the new node will be compared with the old node. When there is no match, the key of the new node will be compared with the old node, so as to find the corresponding old node.

The sameNode function a. keey === B. Keey can be compared with the sameNode function a. keey === B. Therefore, it will be more accurate. If you do not add key, the state of the previous node will be retained, which will cause a series of bugs.

Faster: the uniqueness of the key can be fully utilized by the Map data structure, compared to the time complexity of traversal search O(n),Map time complexity is only O(1), source code:

function createKeyToOldIdx(children, beginIdx, endIdx) {
  let i, key;
  const map = {};
  for (i = beginIdx; i <= endIdx; ++i) {
    key = children[i].key;
    if (isDef(key)) map[key] = i;
  }
  return map;
}
Copy the code

How does v-Model work?

In the VUE project, we mainly used v-Model instructions to create two-way data binding on form input, Textarea, SELECT, etc. We knew that v-Model was essentially just syntax sugar. The V-Model internally uses different attributes for different input elements and throws different events:

  • Text and Textarea elements use value attributes and input events;
  • Checkbox and radio use the Checked attribute and the change event;
  • The SELECT field takes value as prop and change as an event.

Take the input form element for example:

<input v-model='something'> = <input v-bind:value="something" v-on:input="something = $event.target.value"> Copy codeCopy the code

If in a custom component, the V-Model defaults to use a prop named Value and an event named input, as follows:

Parent component: <ModelChild V-model ="message"></ModelChild> sub-component: <div>{{value}}</div> props:{value: String
},
methods: {
  test1(){
     this.$emit('input'.'little red')}},Copy the code

How does v-Model work?

In the VUE project, we mainly used v-Model instructions to create two-way data binding on form input, Textarea, SELECT, etc. We knew that v-Model was essentially just syntax sugar. The V-Model internally uses different attributes for different input elements and throws different events:

  • Text and Textarea elements use value attributes and input events;
  • Checkbox and radio use the Checked attribute and the change event;
  • The SELECT field takes value as prop and change as an event.

Take the input form element for example:

<input V-model ='something'> equivalent to <input v-bind:value="something" V-on :input="something = $event.target.value"> copy codeCopy the code

If in a custom component, the V-Model defaults to use a prop named Value and an event named input, as follows:

Parent: <ModelChild V-model ="message"></ModelChild> Child: <div>{{value}}</div> props:{value: String}, methods: {test1(){this.$emit('input', 'red ')},},Copy the code

What is MVVM?

Model — View — ViewModel (MVVM) is a software architecture design pattern developed by Ken Cooper and Ted Peters, Microsoft WPF and Silverlight architects, as an event-driven programming approach to simplifying user interfaces. Published by John Gossman (also WPF and Silverlight architect) on his blog in 2005

MVVM is derived from the classic Model-View-Controller (MVC) mode. The emergence of MVVM promotes the separation of front-end development and back-end business logic, greatly improving the efficiency of front-end development. The core of MVVM is the ViewModel layer. It is like a value Converter, responsible for transforming the data objects in the Model to make the data easier to manage and use. The layer has two-way data binding with the view layer up and data interaction with the Model layer down through interface requests

(1) View layer

A View is the View layer, the user interface. The front end is mostly built with HTML and CSS.

(2) Model layer

Model is an exponential data Model, which generally refers to various business logic processing and data manipulation carried out by the back end. For the front end, it is the API interface provided by the back end.

(3) ViewModel layer

A ViewModel is a layer of view data generated and maintained by an organization of front-end developers. In this layer, the front-end developer transforms and encapsulates the Model data from the back end to generate a View data Model that meets the expectations of the View layer. It should be noted that the data Model encapsulated by the ViewModel includes the state and behavior of the view, while the data Model of the Model layer only contains the state, such as what this piece of the page shows, what happens when the page loads in, what happens when you click this piece, What happens as this piece of scrolling is all part of the view behavior, the view state and behavior are encapsulated in the ViewModel. This encapsulation allows the ViewModel to fully describe the View layer.

The MVVM framework implements bidirectional binding, so that the contents of the ViewModel are displayed in real time in the View layer. Front-end developers no longer need to inefficiently and cumbersome manipulate the DOM to update the View. The MVVM framework already does the dirty and tiring work, and we developers only need to handle and maintain the ViewModel. Updating the data view automatically updates it accordingly. So the View layer doesn’t represent the data in the Model layer, it represents the data in the ViewModel layer, and the ViewModel is responsible for interacting with the Model layer. This completely decouples the View layer from the Model layer, and this decoupling is critical. It is an important part of the implementation of the front – end separation scheme.

We use a Vue example to illustrate the specific implementation of MVVM, students with Vue development experience should be clear at a glance:

(1) View layer

<div id="app">
    <p>{{message}}</p>
    <button v-on:click="showMessage()">Click me</button>
</div>

Copy the code

(2) ViewModel layer

var app = new Vue({
    el: '#app'.data: {  // Describes the view status
        message: 'Hello Vue! ',},methods: {  // Describes the view behavior
        showMessage(){
            let vm = this; alert(vm.message); }},created(){
        let vm = this;
        // Ajax gets the data from the Model layer
        ajax({
            url: '/your/server/data/api'.success(res){ vm.message = res; }}); }})Copy the code

(3) Model layer

{
    "url": "/your/server/data/api"."res": {
        "success": true."name": "IoveC"."domain": "www.cnblogs.com"}}Copy the code