preface

From the perspective of the former interviewer, this paper sorts out and summarizes some important features and principles of Vue framework in the form of questions, aiming to help the author and readers to test their mastery of Vue. The chapter structure of this article is organized from easy to difficult. It is recommended that the reader read the chapter in order, of course, please feel free to the big guy level. It is hoped that after reading this article, readers will be inspired to think, have a certain understanding of their own Vue, make up for the gaps, and have a better grasp of Vue. Welcome to share your experience ~~~

Hard to arrange for a long time, but also hope to manually thumbs up to encourage ~

Github address:Github.com/fengshi123/…, summarized all the author’s blog, also welcome to follow and star ~

1. Tell me about your understanding of SPA single page. What are its advantages and disadvantages?

SPA (Single-Page Application) loads the appropriate HTML, JavaScript, and CSS only when the Web page is initialized. Once the page is loaded, SPA will not reload or jump to the page because of user operations; Instead, a routing mechanism is used to transform HTML content, UI interaction with the user, and avoid page reloading.

Advantages:

  • User experience is good, fast, content changes do not need to reload the entire page, avoid unnecessary jump and repeat rendering;
  • Based on the above point, SPA is relatively less pressure on the server;
  • The responsibilities of the front and back end are separated, the architecture is clear, the front end carries out interactive logic, and the back end is responsible for data processing;

Disadvantages:

  • The initial loading is time-consuming: In order to realize the functions and display effect of a single-page Web application, JavaScript and CSS need to be loaded uniformly during the page loading, and some pages need to be loaded on demand.
  • Forward and backward routing management: Since the single-page application displays all the content in one page, the forward and backward function of the browser cannot be used, and all page switching needs to establish stack management.
  • SEO is difficult: because all content is dynamically replaced on one page, it has a natural weakness in SEO.

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

V-if is true conditional rendering because it ensures that event listeners and child components within the conditional block are properly destroyed and rebuilt during the toggle; It is also lazy: if the condition is false at the initial render, nothing is done — the condition block is rendered until it becomes true for the first time.

V-show is much simpler — the element is always rendered regardless of the initial condition, and simply switches based on the “display” property of the 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 conditions.

How to dynamically bind Class and Style?

Classes can be dynamically bound using object and array syntax:

  • Object syntax:
<div v-bind:class="{ active: isActive, 'text-danger': hasError }"></div>

data: {
  isActive: true.hasError: false
}
Copy the code
  • Array syntax:
<div v-bind:class="[isActive ? activeClass : '', errorClass]"></div>

data: {
  activeClass: 'active'.errorClass: 'text-danger'
}
Copy the code

Style can also be dynamically bound through object and array syntax:

  • Object syntax:
<div v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>

data: {
  activeColor: 'red'.fontSize: 30
}
Copy the code
  • Array syntax:
<div v-bind:style="[styleColor, styleSize]"></div>

data: {
  styleColor: {
     color: 'red'
   },
  styleSize: {fontSize:'23px'}}Copy the code

4. How to understand the one-way data flow of Vue?

All prop causes a one-way downward binding between parent and child: updates to the parent prop flow down to the child component, but not vice versa. This will prevent the state of the parent component from changing unexpectedly from the child component, which can cause your application’s data flow to be difficult to understand.

Additionally, every time the parent component is updated, all prop in the child component will be refreshed to the latest value. This means that you should not change a prop inside a child component. If you do, Vue will issue an alert in the browser’s console. When the child component wants to modify, it can only send a custom event through $Emit. After receiving the event, the parent component will modify it.

There are two common situations in which you try to change a prop:

  • This prop is used to pass an initial value; The child component next wants to use it as a local prop data. In this case, it is best to define a local data property and use the prop as its initial value:
props: ['initialCounter'].data: function () {
  return {
    counter: this.initialCounter
  }
}
Copy the code
  • The prop is passed in with a raw value and needs to be converted. In this case, it is best to use the value of the prop to define a computed property
props: ['size'].computed: {
  normalizedSize: function () {
    return this.size.trim().toLowerCase()
  }
}
Copy the code

5. What are the differences between Computed and Watch and what are the application scenarios?

Computed: The value of computed is cached. Only when the value of the dependent attribute changes, the value of computed is recalculated the next time the value of computed is obtained.

Watch: More of a “watch” function, similar to the listening callback of some data, every time the listening data changes, the callback will be executed for subsequent operations;

Application scenario:

  • Use Computed when you need to perform numeric computations that depend on other data because the caching feature of computed avoids having to recalculate the value every time it is fetched.

  • Watch should be used when we need to perform an asynchronous or expensive operation when data changes. Using the Watch option allows us to perform an asynchronous operation (access an API), limits how often we perform the operation, and sets the intermediate state until we get the final result. These are things that computational properties can’t do.

6. Can Vue detect changes in an array item assigned directly?

Due to JavaScript limitations, Vue cannot detect the following array changes:

  • When you set an array entry directly using an index, for example:vm.items[indexOfItem] = newValue
  • When you change the length of an array, for example:vm.items.length = newLength

To solve the first problem, Vue provides the following operations:

// Vue.set
Vue.set(vm.items, indexOfItem, newValue)
$set, an alias for vue.set
vm.$set(vm.items, indexOfItem, newValue)
// Array.prototype.splice
vm.items.splice(indexOfItem, 1, newValue)
Copy the code

To solve the second problem, Vue provides the following operations:

// Array.prototype.splice
vm.items.splice(newLength)
Copy the code

7. What is your understanding of the Vue life cycle?

(1) What is the life cycle?

A Vue instance has a complete life cycle, which is called the life cycle of Vue, from start to create, initialize the data, compile the template, mount Dom -> render, update -> render, unload, etc.

(2) The role of each life cycle

The life cycle describe
beforeCreate When the component instance is created, before the component properties take effect
created The component instance is fully created and the properties are bound, but the real DOM has not yet been generated and $EL is not yet available
beforeMount Called before the mount begins: the relevant render function is called for the first time
mounted El is replaced by the newly created VM.$el, and the hook is called after the instance is mounted
beforeUpdate Called before component data is updated and occurs before the virtual DOM is patched
update After the component data is updated
activited Keep-alive only, called when a component is activated
deactivated Keep-alive only, called when a component is destroyed
beforeDestory Called before component destruction
destoryed Called after the component is destroyed

(3) Schematic diagram of life cycle

Vue’s parent and child component lifecycle hook function execution sequence?

Vue’s parent and child lifecycle hook functions are executed in the following four parts:

  • 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

9. In what lifecycle is the asynchronous request invoked?

This function can be called in the created, beforeMount, and Mounted hook functions, because data is created in these three hook functions and can be assigned to the data returned by the server. However, I recommend calling asynchronous requests in the created hook function, because calling asynchronous requests in the created hook function has the following advantages:

  • Faster access to server data, reduce page loading time;
  • SSR does not support beforeMount and Mounted hook functions, so it is placed in created to facilitate consistency.

10. At what stage can I access the operational DOM?

Before the hook function mounted is called, Vue has already mounted the compiled template to the page, so you can access the DOM from mounted. The specific vUE life cycle diagram can be seen below, understand the operation of the entire life cycle of each stage, about the life cycle related interview questions will not be difficult to you.

11. Can a parent component listen to the lifecycle of a child component?

If the Parent component (Parent) and the Child component (Child) are mounted, the Parent component (Parent) hears that the mounted component is mounted. If the Parent component (Parent) hears that the Child is mounted, the Parent component (Child) hears that the mounted component is mounted.

// Parent.vue
<Child @mounted="doSomething"/>
    
// Child.vue
mounted() {
  this.$emit("mounted");
}
Copy the code

$emit triggers the parent component event manually. A simpler way is to listen when the parent component references the child component via @hook, as shown below:

// Parent.vue
<Child @hook:mounted="doSomething" ></Child>

doSomething() {
   console.log('Parent component listens to mounted hook function... ');
},
    
// Child.vue
mounted(){
   console.log('Child component fires mounted hook function... ');
},    
    
// The above output sequence is:
// The child component triggers the Mounted hook function...
// The parent listens to the Mounted hook function...
Copy the code

Of course, @hook method can not only listen on mounted, other life cycle events, such as: created, updated, etc.

What do you know about keep-alive?

Keep-alive is a component built into Vue that allows contained components to retain state and avoid rerendering. It has the following features:

  • Generally used in combination with routing and dynamic components to cache components;
  • Provide include and exclude attributes. Both support strings or regular expressions. Include means that only components with matching names will be cached.
  • The hook functions activated and deactivated are activated when the component is activated and deactivated when the component is removed.

13. Why is data a function?

Why does data in a component have to be a function and then return an object, whereas in a new Vue instance, data can be an object?

// data data() {return {message: "child component ", childName:this.name}} // new Vue new Vue({el: '#app', router, template: '<App/>', components: {App} })Copy the code

If data is an object in a component, then there is no scope isolation. If data is a function in a component, then each instance can maintain a separate copy of the returned object. Data property values between component instances do not affect each other; Instances of new Vue, on the other hand, are not reused, so there is no reference object problem.

14. How does the V-Model work?

In our VUE project, we mainly use the V-Model directive to create two-way data binding on elements such as form input, Textarea, select, etc. We know that v-Model is essentially just syntax sugar. The V-Model internally uses different attributes for different input elements and throws different events:

  • Text and Textarea elements use the value attribute and input event;
  • Checkbox and radio use the Checked property and the change event;
  • The select field takes value as a 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 the code

If in a custom component, v-Model will use a prop named value and an event named Input by default, as shown below:

</ModelChild> props:{value: String}, methods: </ModelChild> props:{value: String}, methods: {test1(){this.$emit('input', 'emit ')},},Copy the code

15. What are the communication methods between Vue components?

The communication between Vue components is one of the knowledge points often tested in the interview. This question is similar to the open question. The more ways you answer, the more points you will get, indicating that you are more proficient in Vue. Vue inter-component communication refers to the following three types of communication: parent-child communication, intergenerational communication, and sibling communication. We will introduce each type of communication and explain which type of inter-component communication this method can be applied to.

(1)props / $emitSuitable for communication between parent and child components

This method is the basis of Vue component. I believe that most students can hear it well, so I will not introduce it by example here.

(2)ref$parent / $childrenSuitable for communication between parent and child components

  • ref: If used on a normal DOM element, the reference refers to the DOM element. If used on a child component, the reference points to the component instance
  • $parent / $children: Access the parent/child instance

(3)EventBus ($EMIT / $ON)Suitable for communication between father and son, intergenerational and brother components

This method uses an empty Vue instance as the central event bus (event center), which can be used to trigger and listen for events, thus enabling communication between any component, including parent, generation, and sibling components.

(4)$attrs/$listenersSuitable for intergenerational communication

  • $attrs: contains feature bindings (except class and style) whose parent scope is not recognized (and retrieved) by prop. When a component does not declare any prop, all parent scope bindings (except class and style) are included and can be passedv-bind="$attrs"Pass in internal components. Usually used in conjunction with the inheritAttrs option.
  • $listeners: contains a V-on event listener in the parent scope (without.native modifier). It can go throughv-on="$listeners"Passing in internal components

(5)provide / injectSuitable for intergenerational communication

The ancestor component supplies variables via the provider, and the descendant component injects variables via the inject. The Provide/Inject API mainly solves the communication problem between cross-level components, but its use scenario is that the child component obtains the state of the parent component, and the cross-level components establish a kind of active provision and dependency injection relationship.

(6) Vuex is suitable for father and son, intergenerational, brother components communication

Vuex is a state management pattern developed specifically for vue.js applications. At the heart of every Vuex app is the store. A “store” is basically a container that contains most of the states in your app.

  • The state store of Vuex is responsive. When the Vue component reads the state from the store, if the state in the store changes, the corresponding component will be updated accordingly.
  • The only way to change the state in a Store is to explicitly commit the mutation. This makes it easy to track each state change.

16. Have you ever used Vuex?

Vuex is a state management pattern developed specifically for vue.js applications. At the heart of every Vuex app is the store. A “store” is basically a container that contains most of the states in your app.

(1) The state storage of Vuex is responsive. When the Vue component reads the state from the store, if the state in the store changes, the corresponding component will be updated accordingly.

(2) The only way to change the state in a Store is to explicitly commit the mutation. This makes it easy to track each state change.

It mainly includes the following modules:

  • State: A data structure that defines the State of the application, where you can set the default initial State.
  • Getters: To allow a component to get data from a Store, the mapGetters helper function simply maps getters in a Store to locally computed properties.
  • Mutation: is the only method to change the state in store and must be a synchronous function.
  • Action: Used for submitting mutations rather than directly changing state and can include any asynchronous operation.
  • Module: Allows a single Store to be split into multiple stores and stored in a single state tree.

17. Have you ever used Vue SSR? Tell me something about the SSR?

Vue.js is a framework for building client-side applications. By default, the Vue component can be exported to the browser to generate and manipulate the DOM. However, you can also render the same component as HTML strings on the server side, send them directly to the browser, and finally “activate” those static tags as a fully interactive application on the client side.

SSR roughly means that vue renders the entire HTML fragment of the tag on the client side and completes the work on the server side. The HTML fragment formed by the server side is directly returned to the client side. This process is called server side rendering.

The advantages and disadvantages of server-side rendering SSR are as follows:

(1) Advantages of server-side rendering:

  • Better SEO: Because the content of the SPA page is obtained through Ajax, and the search engine crawl tool will not wait for Ajax asynchronous completion of the page to crawl the content, so in the SPA is to crawl the page through Ajax to get the content; SSR is directly returned by the server to the rendered page (the data is already contained in the page), so search engine crawler tools can crawl the rendered page;
  • Faster content arrival time (faster first screen loading) : SPA will wait for all Vue compiled JS files to be downloaded before rendering the page. It takes a certain amount of time to download files, so the first screen rendering needs a certain amount of time. SSR renders the page directly by the server and returns to display, without waiting to download JS file and render again, so SSR has faster content arrival time;

(2) Disadvantages of server-side rendering:

  • More development constraints: for example, server-side rendering only supports the beforCreate and Created hook functions, which results in some external extension libraries requiring special treatment to run in server-side rendering applications. And unlike SPA, a completely static single-page application that can be deployed on any static file server, the server-side rendering application needs to be in the Node.js Server runtime environment;
  • More server load: Rendering a full application in Node.js is obviously much more CPU-intensive than a server that only serves static files, so if you expect to use it in high traffic environments, Prepare your server load and use your caching strategy wisely.

If there is no SSR development experience of students, you can refer to the author of another SSR practice article “Vue SSR pit journey”, SSR project construction and with the source code.

18. How many vue-router routing modes are available?

Vue-router has three routing modes: Hash, History, and Abstract. The corresponding source code is as follows:

switch (mode) {
  case 'history':
	this.history = new HTML5History(this, options.base)
	break
  case 'hash':
	this.history = new HashHistory(this, options.base, this.fallback)
	break
  case 'abstract':
	this.history = new AbstractHistory(this, options.base)
	break
  default:
	if(process.env.NODE_ENV ! = ='production') {
	  assert(false.`invalid mode: ${mode}`)}}Copy the code

The three routing modes are described as follows:

  • Hash: The HASH value of the URL is used for routing. Support for all browsers, including those that do not support the HTML5 History Api;

  • History: Relies on the HTML5 History API and server configuration. See the HTML5 History mode;

  • Supports all JavaScript runtime environments, such as the Node.js server side. If no browser API is found, the route is automatically forced into this mode.

19. How do you implement the hash and history routing modes commonly used in vue-Router?

(1) Implementation principle of the hash mode

Early implementations of front-end routing were based on location.hash. The implementation is simple. The value of location.hash is what follows the # in the URL. For example, the following site has a location.hash value of ‘#search’ :

https://www.word.com#search
Copy the code

The implementation of the Hash routing mode is based on the following features:

  • The hash value in the URL is only a state of the client. That is, when a request is sent to the server, the hash part is not sent.
  • Each change in the hash value adds a record to the browser’s access history. So we can use the browser’s back and forward buttons to control the hash switching;
  • You can use the a tag and set the href attribute. When the user clicks the tag, the HASH value of the URL will change. Or use JavaScript to assign loaction.hash and change the HASH value of the URL.
  • We can use the HashChange event to listen for the hash value to jump (render) to the page.

(2) The implementation principle of history mode

HTML5 provides the History API to implement URL changes. The two most important apis are history.pushState() and history.repalcestate (). These two apis allow you to manipulate the browser’s history without refreshing it. The only difference is that the former adds a new history, while the latter directly replaces the current history, as follows:

window.history.pushState(null.null, path);
window.history.replaceState(null.null, path);
Copy the code

The implementation of the History routing pattern is based on the following features:

  • The pushState and repalceState apis operate to implement URL changes;
  • We can use popState events to listen for url changes and jump to the page (rendering).
  • History.pushstate () or history.replacestate () do not trigger popState events, so we need to manually trigger the page jump (render).

20. What is MVVM?

Model-view-viewmodel (MVVM) is a software architecture design pattern developed by Ken Cooper and Ted Peters, Microsoft ARCHITECTS for WPF and Silverlight, as a way to simplify user interface event-driven programming. Published by John Gossman (also WPF and Silverlight architect) on his blog in 2005

MVVM is derived from the classic Model-View-Controller (MVC) pattern. The emergence of MVVM promotes the separation of front-end development and back-end business logic, and greatly improves the efficiency of front-end development. The core of MVVM is the ViewModel layer. It is like a value converter, responsible for the transformation of data objects in the Model to make the data easier to manage and use, the layer up to two-way data binding with the view layer, and down to the Model layer through the interface request for data interaction, the role of up and down. As shown in the figure below:

(1) View layer

View is the View layer, the user interface. The front end is built primarily out of HTML and CSS.

(2) Model

Model refers to the data Model, which generally refers to the business logic processing and data manipulation carried out by the back end, and the API interface provided by the back end for the front end.

(3) ViewModel layer

A ViewModel is a view data layer that is generated and maintained by the front-end developer organization. In this layer, the front-end developer transforms the Model data retrieved from the back end and re-wraps it to generate the View data Model that the View layer expects to use. It is important to note that the data Model encapsulated by the ViewModel includes the state and behavior of the view, whereas the data Model of the Model layer contains only the state, such as what this section of the page shows, what happens when the page loads, what happens when you click on this section, What happens when this piece scrolls is all part of the view behavior (interaction), the view state and behavior is 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 the View layer in real time, and front-end developers no longer need to inefficient and cumbersome manipulation of the DOM to update the View. The MVVM framework has done the dirty part, and we developers only need to handle and maintain the ViewModel. Updating the data view will automatically update accordingly. In this way, the View layer presents not the Model layer’s data, but the ViewModel’s data, and the ViewModel is responsible for the interaction with the Model layer. This completely decouples the View layer and the Model layer. This decoupling is crucial. It is an important part of the implementation of the anterior and posterior separation scheme.

We follow a Vue example to illustrate the specific implementation of MVVM, have Vue development experience of students should be clear:

(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 state of the view
        message: 'Hello Vue! ',},methods: {  // Used to describe 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

21. How does Vue implement bidirectional data binding?

Vue bidirectional data binding mainly refers to: data changes update view, view changes update data, as shown in the figure below:

That is:

  • When the content of the input box changes, the Data in Data changes synchronously. Change of View => Data.
  • When Data in Data changes, the content of the text node changes synchronously. Data => View change.

Among them, changes in View update Data, which can be implemented through event listening, so Vue’s Data bidirectional binding work is mainly how to update View according to Data changes.

Vue implements bidirectional data binding through the following four steps:

Implement a listener Observer: iterate over the data Object, including the properties of the child property Object, using object.defineProperty () to add setters and getters to each property. In this case, if you assign some value to this object, that triggers the setter, so you can listen for changes.

Implement a parser: parse Vue template instructions, replace variables in the template with data, and then initialize the rendering page view, and bind the corresponding nodes of each instruction to update functions, add subscribers to listen to data, once the data has changed, receive notification, call update functions to update data.

Implement a subscriber Watcher: Watcher subscribers are the communication bridge between The Observer and Compile. Their main task is to subscribe to the message of attribute changes in the Observer. When the message of attribute changes is received, the corresponding update function in the Compile parser is triggered.

Implement a subscriber Dep: The subscriber uses a publish-and-subscribe design pattern to collect subscriber Watcher and manage both the listener Observer and subscriber Watcher in a unified manner.

The flowchart of the above four steps is shown as follows. If you don’t understand clearly, you can check the author’s article “0 to 1: Vue Core data Bidirectional Binding” for detailed explanation and code demo examples.

How does the Vue framework implement listening on objects and arrays?

Object.defineproperty () hijack the data, but object.defineProperty () can only hijack attributes, not the whole Object. Similarly, you can’t hijack an array, but we know from using the Vue framework that Vue can detect changes to objects and arrays (partial method operations), so how does it work? Let’s look at the relevant code as follows:

  /** * Observe a list of Array items. */
  observeArray (items: Array<any>) {
    for (let i = 0, l = items.length; i < l; i++) {
      observe(items[i])  // Observe function indicates the change of monitoring data}}/** * Recursive traversal of attributes */
  letchildOb = ! shallow && observe(val)// Observe function indicates the change of monitoring data

Copy the code

By looking at the Vue source section above, we can know that the Vue framework can also listen to objects and arrays (partial method operations) using object.defineProperty () by traversing groups and recursively traversing objects.

23, Proxy and Object. DefineProperty comparison

Proxy has the following advantages:

  • A Proxy can directly listen on objects rather than properties;
  • Proxy can directly listen for array changes.
  • Proxy has up to 13 intercepting methods, not limited to apply, ownKeys, deleteProperty, has and so on, which Object. DefineProperty does not have;
  • Proxy returns a new Object, we can only operate on the new Object to achieve the purpose, but object.defineProperty can only traverse the Object properties directly modify;
  • Proxy as a new standard will be the focus of browser vendors continued performance optimization, that is, the legendary new standard performance dividend;

The advantages of object.defineProperty are as follows:

  • It is compatible with IE9, but Proxy has browser compatibility issues and cannot be polished with Polyfill, so Vue’s authors declare that they will have to wait until the next major release (3.0) to rewrite it with Proxy.

$set() = $set() = $set();

Due to the limitations of modern JavaScript, Vue cannot detect the addition or removal of object properties. Since Vue performs getter/setter transformations on the property when initializing the instance, the property must exist on the data object for Vue to convert it to responsive. Vue provides vue.set (object, propertyName, value)/vm.$set (object, propertyName, value) to add responsive properties to objects. How does the framework itself implement this?

We view the corresponding Vue source: Vue/SRC/core/instance/index. Js

export function set (target: Array<any> | Object, key: any, val: any) :any {
  // Target is an array
  if (Array.isArray(target) && isValidArrayIndex(key)) {
    // Modify the length of the array to avoid the splcie() error caused by index > array length
    target.length = Math.max(target.length, key)
    // Trigger the response using the array splice mutating method
    target.splice(key, 1, val)
    return val
  }
  // Modify the value of the key
  if (key intarget && ! (keyin Object.prototype)) {
    target[key] = val
    return val
  }
  const ob = (target: any).__ob__
  // The target itself is not reactive data
  if(! ob) { target[key] = valreturn val
  }
  // Respond to the attribute
  defineReactive(ob.value, key, val)
  ob.dep.notify()
  return val
}
Copy the code

$set = $set; $set = $set; $set = $set;

  • If the target is an array, use the array’s splice method to trigger the corresponding expression.

  • If the target is an object, the attribute is read for existence, the object is responsive, and finally, if the attribute is to be responsive, it is handled responsively by calling defineReactive (which means that when Vue initializes the object, Method to dynamically add getters and setters to an Object property using object.defineProperty)

25. What are the pros and cons of virtual DOM?

Advantages:

  • Guaranteed performance lower limit: The virtual DOM of the framework needs to be adapted to any operation that may be generated by the upper-layer API. The implementation of some DOM operations must be universal, so its performance is not optimal. But performance is much better than rough DOM manipulation, so the framework’s virtual DOM at least ensures that you can still provide decent performance without having to manually optimize.
  • No manual manipulation of the DOM: We no longer need to manually operate the DOM, just need to write the code logic of the View-Model, according to the virtual DOM and data two-way binding, help us to update the View in a predictable way, greatly improve our development efficiency;
  • Cross-platform: The VIRTUAL DOM is essentially a JavaScript object, and the DOM is strongly platform dependent. In contrast, the virtual DOM can be more easily cross-platform, such as server rendering, WEEX development, and so on.

Disadvantages:

  • Unable to perform extreme optimization: Although the virtual DOM + reasonable optimization is sufficient to meet the performance requirements of most applications, the virtual DOM cannot perform targeted extreme optimization in some applications with high performance requirements.

26. Realization principle of virtual DOM?

The realization principle of virtual DOM mainly includes the following three parts:

  • Using JavaScript object to simulate real DOM tree, real DOM abstract;
  • Diff algorithm – compare the difference between two virtual DOM trees;
  • Pach algorithm – Applies the differences between two virtual DOM objects to the real DOM tree.

If you are not familiar with the above three parts, you can check out the article “Deep Analysis: The Virtual DOM at the core of Vue” written by the author.

What is the role of key in Vue?

The key is the unique token of the vnode in the Vue. With this key, we can perform diff operations more accurately and quickly. Vue’s diff process can be summarized as: OldCh and newCh each have two variables: oldStartIndex, oldEndIndex, and newStartIndex, newEndIndex. They compare the new node to the old node in pairs. There are four ways to compare the old node: NewStartIndex and oldStartIndex, newEndIndex and oldEndIndex, newStartIndex and oldEndIndex, newEndIndex and oldStartIndex, If none of the above four comparisons match, if the key is set, the comparison will be made again using the key. During the comparison, the traversal will move to the middle. Once StartIdx > EndIdx indicates that at least one of oldCh and newCh has been traversed, the comparison will end. For details on the diff process with or without a key, see the author’s article on virtual DOM in Depth: The Virtual DOM at the core of Vue.

The key in Vue is the unique identifier of the vnode in Vue. The diff operation is faster and more accurate

More accurate: since there is no in-place reuse with the key, this can be avoided in the sameNode function a.keey === B.keey comparison. So it will be more accurate.

Faster: Use the key’s uniqueness to generate a map object to obtain the corresponding node, faster than traversal mode, source code as follows:

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

28. What optimizations have you made for the Vue project?

If you have not made a summary of Vue project optimization, you can refer to another article “Vue Project Performance Optimization – Practice Guide” by the author of this paper. This article mainly introduces how to optimize Vue project from 3 big aspects and 22 small aspects in detail.

(1) Code level optimization

  • V-if and V-show are used in different scenarios
  • Computed and Watch are used in different scenarios
  • V-for traversal must add key to item and avoid using v-if at the same time
  • Long list performance optimization
  • Destruction of events
  • Image resources were loaded lazily
  • The route was loaded lazily. Procedure
  • The on-demand introduction of third-party plug-ins
  • Optimized infinite list performance
  • Server render SSR or pre-render

(2) Optimization at the Webpack level

  • Webpack compresses images
  • Reduce redundant code from ES6 to ES5
  • Extract common code
  • Template precompile
  • Extract the CSS for the component
  • Optimize SourceMap
  • Build result output analysis
  • Compilation optimization for the Vue project

(3) Optimization of basic Web technology

  • The gZIP compression function is enabled

  • Browser cache

  • The use of CDN

  • Use Chrome Performance to find Performance bottlenecks

29. What do you know about the upcoming Vue3.0 features?

Vue 3.0 is on its way to release. The goal of Vue 3.0 is to make the Vue core smaller, faster, and more powerful. As a result, Vue 3.0 adds the following new features:

(1) Changes in monitoring mechanisms

3.0 will bring a proxy-based observer implementation that provides full language coverage for reactive tracking. This removes many of the limitations of the object.defineProperty-based implementation in Vue 2:

  • Only properties can be monitored, not objects

  • Detect the addition and removal of attributes;

  • Detect array index and length changes;

  • Supports Map, Set, WeakMap, and WeakSet.

The new Observer also provides the following features:

  • A public API for creating An Observable. This provides a simple and lightweight cross-component state management solution for small to medium scale scenarios.
  • Lazy observation is adopted by default. In 2.x, no matter how large the equation data is, it will be observed at startup. If your data set is large, this can cause significant overhead at startup. In 3.x, only the data used to render the first visible part of the application is observed.
  • More precise notification of changes. In 2.x, forcing a new property to be added with ue. Set causes watcher dependent on the object to be notified of the change. In 3.x, only watcher that depends on a particular property will be notified.
  • Immutable Observable: We can create “immutable” versions of values (even nested properties) unless the system temporarily “unlocks” them internally. This mechanism can be used to freeze prop transfers or changes outside of the Vuex state tree.
  • Better debugging: We can use the new renderTracked and renderTriggered hooks to track exactly when and why components are being rerendered.

(2) Template

There are no major changes to the template, only the scope slots. The 2.x mechanism causes scope slots to be changed and the parent component will be rerendered, while 3.0 changes the scope slots to function mode, which only affects the child component’s rerendering and improves the rendering performance.

Also, vue3.0 will make a series of changes to the render function to make it easier to use the API directly to generate vdom.

(3) Object type component declaration

Components in vue2.x pass in a list of options via declarations. TypeScript uses decorators, which are cumbersome to implement. 3.0 changes the way components are declared to be class-like, making it easier to work with TypeScript.

In addition, vue source code is written in TypeScript instead. In fact, when the function of the code is complex, it is necessary to have a static type system to do some management. Now that VUe3.0 is fully rewritten in TypeScript, it makes it easier to integrate exposed apis with TypeScript. Static type systems are indeed necessary for the maintenance of complex code.

(4) Other changes

The changes in VUe3.0 are comprehensive, only the three main areas are covered above, and there are a few other changes:

  • Support for custom renderers allows WEEX to be extended by custom renderers rather than forking the source code.
  • Support for Fragment (multiple root nodes) and Protal (rendering components in other parts of the DOM) components for special scenarios.
  • Treeshaking optimized for more built-in functionality.

30. Tell me about the biggest pit you’ve ever stepped on with a Vue frame. How was it solved?

Please feel free to share your experiences in the comments section to help prevent others from stepping in the pit again

conclusion

From the perspective of the former interviewer, this paper sorts out and summarizes some important features and principles of Vue framework in the form of questions, aiming to help the author and readers to test their mastery of Vue. Hope to read this article you have help, have inspiration, if there are shortcomings, welcome to criticize correct communication!

Hard to arrange for a long time, but also hope to manually thumbs up to encourage ~

Github address:Github.com/fengshi123/…, summarized all the author’s blog, also welcome to follow and star ~