[Interview questions] 2023vue interview questions

 Dachang interview questions share interview question bank

Front-end and back-end interview question banks (necessary for interviews) Recommended: ★★★★★

Address: front-end interview question bank   web front-end interview question bank VS java back-end interview question bank Daquan

 

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

SPA (single-page application) only loads the corresponding HTML, JavaScript and CSS when the Web page is initialized. Once the page is loaded, SPA will not reload or jump the page due to the user's operation; instead, it uses the routing mechanism to realize the transformation of HTML content, and the UI interacts with the user to avoid page reloading. advantage:

  • The user experience is good and fast, and the content change does not need to reload the entire page, avoiding unnecessary jumps and repeated rendering;
  • Based on the above point, SPA has relatively little pressure on the server;
  • The front-end and back-end responsibilities are separated, the structure is clear, the front-end performs interactive logic, and the back-end is responsible for data processing;

shortcoming:

  • The initial loading takes a lot of time: In order to realize the functions and display effects of single-page web applications, JavaScript and CSS need to be loaded uniformly when loading the page, and some pages are loaded on demand;
  • Forward and backward routing management: Since the single-page application displays all the content in one page, the forward and backward functions of the browser cannot be used, and all page switching needs to establish stack management by itself;
  • SEO is more difficult: Since all content is dynamically replaced and displayed on one page, it has a natural weakness in SEO.

2. What is the difference between v-show and v-if?

v-if is true conditional rendering, as it will ensure that event listeners and child components inside the conditional block are destroyed and rebuilt appropriately during the toggle; also lazy: if the condition is false on initial render, do nothing do - the conditional block won't start rendering until the condition becomes true for the first time. v-show is much simpler - the element is always rendered regardless of the initial condition, and is simply toggled based on the CSS "display" property. Therefore, v-if is suitable for scenarios that rarely change conditions at runtime and does not require frequent switching conditions; v-show is suitable for scenarios that require very frequent switching conditions.

3. How to dynamically bind Class and Style?

Class can be dynamically bound through object syntax and array syntax:

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

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

data: {
  activeClass: 'active',
  errorClass: 'text-danger'
}

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

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

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

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

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

All props form a single downward binding between their parent and child props: updates to the parent prop flow down to the child components, but not the other way around. This prevents accidental changes to the parent component's state from child components, which can make your app's data flow difficult to understand. In addition, every time the parent component is updated, all props in the child component will be refreshed with the latest values. This means you should not change props inside a child component. If you do this, Vue will issue a warning in the browser's console. When a child component wants to modify it, it can only send a custom event through $emit, and the parent component will modify it after receiving it. There are two common situations when trying to mutate a prop:

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

5. What is the difference between computed and watch and the application scenarios?

computed: is a computed attribute, dependent on other attribute values, and the value of computed is cached, only when the value of the attribute it depends on changes, the value of computed will be recalculated the next time the value of computed is obtained; watch: more "observation "The function is similar to the monitoring callback of some data. Whenever the monitored data changes, the callback will be executed for subsequent operations; application scenarios:

  • When we need to perform numerical calculations and depend on other data, computed should be used, because the cache feature of computed can be used to avoid recalculation every time a value is obtained;
  • When we need to perform asynchronous or expensive operations when data changes, we should use watch, using the watch option allows us to perform asynchronous operations (access an API), limit the frequency we perform the operation, and before we get the final result , which sets the intermediate state. These are things that computed properties cannot do.

6. When directly assigning a value to an array item, can Vue detect the change?

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

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

To solve the first problem, Vue provides the following operation methods:

// Vue.set
Vue.set(vm.items, indexOfItem, newValue)
// vm.$set,Vue.set的一个别名
vm.$set(vm.items, indexOfItem, newValue)
// Array.prototype.splice
vm.items.splice(indexOfItem, 1, newValue)

To solve the second problem, Vue provides the following operation methods:

// Array.prototype.splice
vm.items.splice(newLength)

7. Tell me about your understanding of the Vue life cycle?

(1) What is the life cycle? A Vue instance has a complete life cycle, that is, a series of processes from the beginning of creation, initialization of data, compilation of templates, mounting of Dom -> rendering, update -> rendering, unloading, etc. We call this the life cycle of Vue. (2) Function life cycle description of each life cycle

beforeCreate When the component instance is created, before the component's properties take effect
created The component instance has been fully created, and the properties are also bound, but the real dom has not been generated, and $el is not yet available
beforeMount Called before the mount starts: the associated render function is called for the first time
mounted This hook is called after el is replaced by the newly created vm.$el and mounted to the instance
beforeUpdate Called before the component data is updated, which occurs before the virtual DOM is patched
update After component data update
activited Exclusive to keep-alive, called when the component is activated
deadctivated Exclusive to keep-alive, called when the component is destroyed
beforeDestory Called before the component is destroyed
destoryed Called after the component is destroyed

(3) Schematic diagram of life cycle

8. What is the execution order of Vue's parent component and child component lifecycle hook functions? The execution sequence of Vue's parent component and child component lifecycle hook functions can be classified into the following four parts:

  • Load the rendering process

father beforeCreate -> father created -> father beforeMount -> child beforeCreate -> child created -> child beforeMount -> child mounted -> father mounted

  • Subcomponent update process

father beforeUpdate -> child beforeUpdate -> child updated -> father updated

  • Parent component update process

father beforeUpdate -> father updated

  • destruction process

father beforeDestroy -> child beforeDestroy -> child destroyed -> father destroyed

9. In which life cycle is the asynchronous request called?

It can be called in the hook functions created, beforeMount, and mounted, because in these three hook functions, data has already been created, and the data returned by the server can be assigned. But I recommend calling asynchronous requests in the created hook function, because calling asynchronous requests in the created hook function has the following advantages:

  • Can get server data faster and reduce page loading time;
  • ssr does not support beforeMount and mounted hook functions, so putting them in created will help consistency;

10. At what stage can the DOM be accessed and operated?

Before the hook function mounted is called, Vue has mounted the compiled template to the page, so the DOM can be accessed and manipulated in mounted. The specific life cycle diagram of vue can be seen as follows. After understanding the operations of each stage of the entire life cycle, you will not be troubled by interview questions related to the life cycle.

 

Dachang interview questions share interview question bank

Front-end and back-end interview question banks (necessary for interviews) Recommended: ★★★★★

Address: front-end interview question bank   web front-end interview question bank VS java back-end interview question bank Daquan

 

11. Can the parent component monitor the life cycle of the child component?

For example, if there is a parent component Parent and a child component Child, if the parent component monitors that the child component is mounted, it will do some logic processing, which can be achieved by the following writing method:

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

// Child.vue
mounted() {
  this.$emit("mounted");
}

The above needs to manually trigger the event of the parent component through $emit. The simpler way is to listen to it through @hook when the parent component references the child component, as shown below:

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

doSomething() {
   console.log('父组件监听到 mounted 钩子函数 ...');
},

//  Child.vue
mounted(){
   console.log('子组件触发 mounted 钩子函数 ...');
},    

// 以上输出顺序为:
// 子组件触发 mounted 钩子函数 ...
// 父组件监听到 mounted 钩子函数 ...

Of course, the @hook method can not only monitor mounted, but also other life cycle events, such as created, updated, etc. can be monitored.

12. Tell me about your understanding of keep-alive?

keep-alive is a built-in component of Vue, which can preserve the state of the contained components and avoid re-rendering. It has the following characteristics:

  • Generally used in conjunction with routing and dynamic components for caching components;
  • Provide include and exclude attributes, both of which support strings or regular expressions, include means that only components with matching names will be cached, and exclude means that any components with matching names will not be cached, and exclude has a higher priority than include;
  • Corresponding to the two hook functions activated and deactivated, when the component is activated, the hook function activated is triggered, and when the component is removed, the hook function deactivated is triggered.

13. Why is data in the component a function?

Why must the data in the component be a function, and then return an object, but in the new Vue instance, data can be an object directly?

// data
data() {
  return {
    message: "子组件",
    childName:this.name
  }
}

// new Vue
new Vue({
  el: '#app',
  router,
  template: '<App/>',
  components: {App}
})

Because the component is used for reuse, and the object in JS is a reference relationship, if the data in the component is an object, then the scope is not isolated, and the data attribute values ​​​​in the subcomponents will affect each other. If the data option in the component is a function, each instance can maintain an independent copy of the returned object, and the data attribute values ​​​​between component instances will not affect each other; and the instance of new Vue will not be reused, so there is no reference object The problem.

14. What is the principle of v-model?

In the vue project, we mainly use the v-model instruction to create two-way data binding on form input, textarea, select and other elements. We know that v-model is essentially just syntactic sugar, and v-model is used internally for different input elements different properties and throw different events:

  • The text and textarea elements use the value attribute and the input event;
  • checkbox and radio use checked attribute and change event;
  • The select field has value as prop and change as event.

Take the input form element as an example:

<input v-model='something'>

相当于

<input v-bind:value="something" v-on:input="something = $event.target.value">

If in a custom component, v-model will by default utilize a prop named value and an event named input, as follows:

父组件:
<ModelChild v-model="message"></ModelChild>

子组件:
<div>{
   
   {value}}</div>

props:{
    value: String
},
methods: {
  test1(){
     this.$emit('input', '小红')
  },
},

15. What are the ways of communication between Vue components?

Communication between Vue components is one of the knowledge points that are often tested in interviews. This question is a bit similar to an open question. The more methods you answer, the more points you will get, which shows that you are more proficient in Vue. Communication between Vue components only refers to the following three types of communication: parent-child component communication, intergenerational component communication, and sibling component communication. Below we will introduce each communication method and explain which type of component communication this method is applicable to. (1) props / $emit Applicable parent-child component communication This method is the basis of Vue components, I believe most students have heard it well, so I will not introduce examples here. (2)  Communicate ref with  applicable parent-child components$parent / $children

  • ref: If used on a normal DOM element, the reference points to the DOM element; if used on a child component, the reference points to the component instance

  • $parent /  $children: Access parent/child instances

(3) EventBus ($emit / $on) Applicable to parent-child, intergenerational, and sibling component communication. This method uses an empty Vue instance as the central event bus (event center), and uses it to trigger events and listen to events, thereby realizing communication between any components, including parent-child , intergenerational, sibling components. (4) $attrs/ $listeners Applicable to intergenerational component communication

  • $attrs: Contains attribute bindings (except class and style) that are not recognized (and acquired) by props in the parent scope. When a component does not declare any props, all parent scope bindings (except class and style) are included here, and can be passed to  v-bind="$attrs" internal components. Usually used in conjunction with the inheritAttrs option.
  • $listeners: Contains v-on event listeners in the parent scope (without the .native modifier). It can be  v-on="$listeners" passed to internal components by

(5) provide / inject Applicable to intergenerational component communication Provide variables through provider in ancestor components, and then inject variables through inject in descendant components. The provide / inject API mainly solves the communication problem between cross-level components, but its usage scenario is mainly that the sub-components obtain the state of the upper-level components, and a relationship between active provision and dependency injection is established between cross-level components. (6) Vuex is suitable for parent-child, intergenerational, and sibling component communication. Vuex is a state management model specially developed for Vue.js applications. At the heart of every Vuex application is the store. A "store" is basically a container that holds most of your application's state.

  • Vuex's state store is reactive. When the Vue component reads the state from the store, if the state in the store changes, the corresponding component will be efficiently updated accordingly.
  • The only way to change the state in the store is to explicitly commit the mutation. This allows us to easily track every 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 application is the store. A "store" is basically a container that holds most of your application's state. (1) Vuex's state storage is responsive. When the Vue component reads the state from the store, if the state in the store changes, the corresponding component will be efficiently updated accordingly. (2) The only way to change the state in the store is to explicitly commit the mutation. This allows us to easily track every state change. It mainly includes the following modules:

  • State: defines the data structure of the application state, where the default initial state can be set.
  • Getter: Allows components to get data from the Store. The mapGetters helper function simply maps the getters in the store to local computed properties.
  • Mutation: is the only way to change the state in the store, and must be a synchronous function.
  • Action: It is used to submit a mutation instead of directly changing the state, and can contain any asynchronous operation.
  • Module: Allows a single Store to be split into multiple stores and stored in a single state tree at the same time.

17. Have you ever used Vue SSR? Talk about SSR?

Vue.js is a framework for building client-side applications. By default, Vue components can be output in the browser to generate DOM and manipulate DOM. However, it is also possible to render the same component as HTML strings on the server, send them directly to the browser, and finally "activate" these static markup as a fully interactive application on the client. Namely: SSR roughly means that vue renders the entire html fragment of the label on the client side and completes the work on the server side, and the html fragment formed by the server side is directly returned to the client. 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 crawler will not wait for Ajax to complete asynchronously before crawling the content of the page, so it is impossible to crawl the page obtained through Ajax in the SPA Content; while SSR returns the rendered page directly from the server (the data is already included in the page), so search engine crawling tools can grab the rendered page;
  • Faster content arrival time (first screen loads faster): SPA will wait for all Vue compiled js files to be downloaded before starting page rendering. File downloads take a certain amount of time, so first screen rendering requires A certain period of time; SSR directly renders the page directly from the server and returns it for display, without waiting to download the js file and then render it, so SSR has a faster content arrival time;

(2) Disadvantages of server-side rendering:

  • More restrictions on development conditions: For example, server-side rendering only supports two hook functions, beforCreate and created, which will cause some external extension libraries to require special handling in order to run in server-side rendering applications; and can be deployed in any static file Unlike the fully static single-page application SPA on the server, the server-side rendering application needs to be in the Node.js server operating environment;
  • More server load: Rendering a full application in Node.js is obviously more CPU-intensive than a server that just serves static files (CPU-intensive - CPU-intensive), so if you expect high-traffic environments ( high traffic ), prepare for server load accordingly, and use caching strategies judiciously.

If you have no experience in SSR development, you can refer to another SSR practice article "Vue SSR Stepping Pit Journey" by the author of this article, which contains SSR project construction and project source code.

18. How many routing modes does vue-router have?

Vue-router has 3 routing modes: hash, history, abstract, and 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}`)
    }
}

Among them, the descriptions of the three routing modes are as follows:

  • hash: Use the URL hash value for routing. Support all browsers, including browsers that do not support HTML5 History Api;
  • history : depends on HTML5 History API and server configuration. For details, you can view the HTML5 History mode;
  • abstract : Support all JavaScript runtime environments, such as Node.js server-side. Routers are automatically forced into this mode if no browser API is found.

19. Can you talk about the implementation principles of the commonly used hash and history routing modes in vue-router?

(1) Implementation principle of hash mode The early implementation of front-end routing was based on location.hash. The realization principle is very simple, the value of location.hash is the content after # in the URL. For example, the following website has a location.hash value of '#search':

https://www.word.com#search

The implementation of hash routing mode is mainly based on the following characteristics:

  • The hash value in the URL is only a state of the client, that is to say, when a request is made to the server, the hash part will not be sent;
  • A change in the hash value will add a record to the browser's access history. Therefore, we can control hash switching through the back and forward buttons of the browser;
  • You can pass the a tag and set the href attribute. When the user clicks on this tag, the hash value of the URL will change; or use JavaScript to assign a value to loaction.hash to change the hash value of the URL;
  • We can use the hashchange event to monitor changes in the hash value, thereby jumping (rendering) the page.

(2) Implementation principle of history mode HTML5 provides History API to realize URL changes. Among them, there are two main APIs: history.pushState() and history.repalceState(). These two APIs can manipulate the browser's history without refreshing it. The only difference is that the former is to add a new history record, and the latter is to directly replace the current history record, as shown below:

window.history.pushState(null, null, path);
window.history.replaceState(null, null, path);

The implementation of the history routing mode is mainly based on the following characteristics:

  • PushState and repalceState two APIs to operate and implement URL changes;
  • We can use the popstate event to monitor the change of the url, so as to jump (render) the page;
  • history.pushState() or history.replaceState() will not trigger the popstate event, then we need to manually trigger the page jump (rendering).

20. What is MVVM?

Model–View–ViewModel (MVVM) is a software architectural design pattern, developed by Microsoft WPF and Silverlight architects Ken Cooper and Ted Peters, is an event-driven programming method that simplifies the user interface. Published by John Gossman (also the architect of WPF and Silverlight) on his blog in 2005. MVVM is derived from the classic Model–View–Controller (MVC) pattern. The emergence of MVVM promotes front-end development and back-end business logic. The separation of the front-end development greatly improves the efficiency of front-end development. The core of MVVM is the ViewModel layer, which is like a transfer station (value converter), responsible for converting the data objects in the Model to make the data easier to manage and use. This layer Two-way data binding with the view layer upwards, and data interaction with the Model layer through interface requests downwards, which acts as a link between the top and the bottom. As shown below:

 

 (1) View layer View is the view layer, that is, the user interface. The front end is mostly built with HTML and CSS. (2) Model layer Model refers to the data model, which generally refers to various business logic processing and data manipulation performed by the backend. For the frontend, it is the api interface provided by the backend. (3) ViewModel layer ViewModel is a view data layer generated and maintained by front-end developers. At this layer, the front-end developers convert and process the Model data obtained from the back-end, and perform secondary packaging to generate a view data model that meets the expectations of the View layer. It should be noted that the data model encapsulated by ViewModel includes the state and behavior of the view, while the data model of the Model layer only includes state, such as what is displayed on this part of the page, and what happens when the page is loaded, click here What happens in one piece, what happens when this piece is scrolled, these all belong to the view behavior (interaction), and the view state and behavior are encapsulated in the ViewModel. Such encapsulation enables ViewModel to fully describe the View layer. The MVVM framework implements two-way binding, so that the content of the ViewModel will be displayed in the View layer in real time. Front-end developers no longer need to update the view by manipulating the DOM inefficiently and troublesomely. The MVVM framework has already done the dirtiest and most tiring part. , our developers only need to process and maintain the ViewModel, and updating the data view will automatically update accordingly. In this way, the View layer does not display the data of the Model layer, but the data of the ViewModel. The ViewModel is responsible for interacting with the Model layer, which completely decouples the View layer and the Model layer. This decoupling is crucial. It is the front-end and back-end An important part of the implementation of the separation scheme. We will 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>

(2) ViewModel layer

var app = new Vue({
    el: '#app',
    data: {  // 用于描述视图状态
        message: 'Hello Vue!', 
    },
    methods: {  // 用于描述视图行为
        showMessage(){
            let vm = this;
            alert(vm.message);
        }
    },
    created(){
        let vm = this;
        // Ajax 获取 Model 层的数据
        ajax({
            url: '/your/server/data/api',
            success(res){
                vm.message = res;
            }
        });
    }
})

(3) Model layer

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

21. How does Vue implement two-way data binding?

Vue data two-way binding mainly refers to: data changes update the view, and view changes update the data, namely:

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

Among them, updating Data when View changes can be realized through event monitoring, so the work of Vue's two-way data binding is mainly how to update View according to Data changes. Vue mainly implements two-way data binding through the following four steps: Implement a listener Observer: traverse the data object, including the properties of the sub-property object, and use Object.defineProperty() to add setters and getters to the properties. In this case, assigning a value to this object will trigger the setter, and then the data change can be monitored. Implement a parser Compile: parse the Vue template instructions, replace the variables in the template with data, then initialize the rendering page view, bind the node corresponding to each instruction with an update function, add subscribers to monitor data, and once the data is available Change, receive a notification, call the update function to update the data. Implement a Subscriber Watcher: Watcher Subscriber is the communication bridge between Observer and Compile. The main task is to subscribe to the message of property value change in Observer. When receiving the message of property value change, trigger the corresponding update function. Implement a subscriber Dep: The subscriber adopts the publish-subscribe design pattern, which is used to collect subscriber Watchers and manage the listener Observer and subscriber Watcher in a unified manner. The flow chart of the above four steps is shown as follows. If some students don’t understand clearly, you can check the author’s article "0 to 1 Mastery: Two-way Data Binding of Vue Core", which is a detailed explanation. , and code demo examples.

22. How does the Vue framework realize the monitoring of objects and arrays?

If you are asked how Vue implements two-way data binding, everyone will definitely answer that the data is hijacked through Object.defineProperty(), but Object.defineProperty() can only hijack the data of the property, not the entire object. In the same way, arrays cannot be hijacked, but we all know that Vue can detect changes in objects and arrays (operations of some methods) when using the Vue framework, so how does it achieve it? We view 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 功能为监测数据的变化
    }
  }

  /**
   * 对属性进行递归遍历
   */
  let childOb = !shallow && observe(val) // observe 功能为监测数据的变化

 

Through the above part of the Vue source code review, we can know that the Vue framework traverses the array and recursively traverses the object, so that Object.defineProperty() can also be used to monitor objects and arrays (operations of some methods).

23. Pros and Cons of Proxy and Object.defineProperty

The advantages of Proxy are as follows:

  • Proxy can directly monitor objects instead of properties;
  • Proxy can directly monitor the changes of the array;
  • Proxy has as many as 13 interception methods, not limited to apply, ownKeys, deleteProperty, has, etc. Object.defineProperty does not have;
  • Proxy returns a new object, we can only operate the new object to achieve the purpose, and Object.defineProperty can only traverse the object properties and directly modify;
  • As a new standard, Proxy will be subject to continuous performance optimization by browser manufacturers, which is the performance bonus of the legendary new standard;

The advantages of Object.defineProperty are as follows:

  • It has good compatibility and supports IE9, but Proxy has browser compatibility problems, and it cannot be smoothed out with polyfill, so the author of Vue declares that it needs to wait until the next major version (3.0) to rewrite it with Proxy.

24. How does Vue use vm.$set() to solve the problem that the object's new property cannot respond?

Due to the limitations of modern JavaScript, Vue cannot detect the addition or removal of object properties. Since Vue performs getter/setter conversion on the property when initializing the instance, the property must exist on the data object for Vue to convert it to reactive. But Vue provides  Vue.set (object, propertyName, value) / vm.$set (object, propertyName, value)to add responsive properties to objects, so how does the framework itself implement it? Let's look at the corresponding Vue source code:vue/src/core/instance/index.js

export function set (target: Array<any> | Object, key: any, val: any): any {
  // target 为数组
  if (Array.isArray(target) && isValidArrayIndex(key)) {
    // 修改数组的长度, 避免索引>数组长度导致splcie()执行有误
    target.length = Math.max(target.length, key)
    // 利用数组的splice变异方法触发响应式
    target.splice(key, 1, val)
    return val
  }
  // key 已经存在,直接修改属性值
  if (key in target && !(key in Object.prototype)) {
    target[key] = val
    return val
  }
  const ob = (target: any).__ob__
  // target 本身就不是响应式数据, 直接赋值
  if (!ob) {
    target[key] = val
    return val
  }
  // 对属性进行响应式处理
  defineReactive(ob.value, key, val)
  ob.dep.notify()
  return val
}

We can see from the above source code that the realization principle of vm.$set is:

  • If the target is an array, directly use the splice method of the array to trigger the corresponding expression;
  • If the target is an object, it will first judge whether the attribute exists and whether the object is responsive. Finally, if you want to perform responsive processing on the attribute, you need to call the defineReactive method to perform responsive processing (the defineReactive method is Vue when initializing the object. Properties use the Object.defineProperty method called by the ability to dynamically add getters and setters)

25. What are the advantages and disadvantages of virtual DOM?

advantage:

  • Guarantee the lower limit of performance: The virtual DOM of the framework needs to adapt to any operations that may be generated by the upper-layer API, and the implementation of some of its DOM operations must be universal, so its performance is not optimal; but compared to the rough DOM operation performance It is much better, so the virtual DOM of the framework can at least guarantee that you can still provide good performance without manual optimization, that is, the lower limit of guaranteed performance;
  • No need to manually operate DOM: We no longer need to manually operate DOM, we only need to write the code logic of View-Model, the framework will bind the virtual DOM and data two-way, help us update the view in a predictable way, greatly improve our development efficiency;
  • Cross-platform: Virtual DOM is essentially a JavaScript object, and DOM is strongly related to the platform. In contrast, virtual DOM can be more convenient for cross-platform operations, such as server rendering, weex development, etc.

shortcoming:

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

26. What is the realization principle of virtual DOM?

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

  • Use JavaScript objects to simulate the real DOM tree and abstract the real DOM;

  • diff algorithm — compare the differences between two virtual DOM trees;

  • The pach algorithm — applies the difference of two virtual DOM objects to the real DOM tree.

If you don’t know much about the above 3 parts, you can check out another article written by the author of this article that explains virtual DOM in detail "In-depth Analysis: Virtual DOM at the Core of Vue"

27. What is the function of key in Vue?

key is the unique mark of vnode in Vue, through this key, our diff operation can be more accurate and faster. The diff process of Vue can be summarized as: oldCh and newCh each have two head and tail variables oldStartIndex, oldEndIndex and newStartIndex, newEndIndex, they will compare the new node and the old node in pairs, that is, there are 4 comparison methods in total: newStartIndex and oldStartIndex , newEndIndex and oldEndIndex, newStartIndex and oldEndIndex, newEndIndex and oldStartIndex, if none of the above 4 comparisons match, if the key is set, the key will be used for comparison again. During the comparison process, the traversal will lean towards the middle, once StartIdx > EndIdx indicates that at least one of oldCh and newCh has been traversed, and the comparison will end. For the diff process of whether there is a key or not, you can check another article written by the author to explain the virtual DOM in detail "In-depth analysis: virtual DOM at the core of Vue". With this key, our diff operation can be more accurate, faster and more accurate: because the key is not in-place multiplexing, in-place  a.key === b.key multiplexing can be avoided in the sameNode function comparison. So it will be more accurate. Faster: Use the uniqueness of the key to generate a map object to obtain the corresponding node, which is faster than the traversal method. The source code is 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
}

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

If you haven’t optimized and summarized the Vue project, you can refer to another article by the author of this article "Vue Project Performance Optimization-Practice Guide". The article mainly introduces how to implement Vue in detail from 3 major aspects and 22 small aspects. Project optimization. (1) Optimization at the code level

  • v-if and v-show distinguish usage scenarios
  • Computed and watch differentiate usage scenarios
  • v-for traversal must add key to item, and avoid using v-if at the same time
  • Long list performance optimization
  • event destruction
  • Lazy loading of image resources
  • Routing lazy loading
  • On-demand introduction of third-party plug-ins
  • Optimize infinite list performance
  • Server-side rendering SSR or pre-rendering

(2) Optimization at the Webpack level

  • Webpack compresses images
  • Reduce redundant code from ES6 to ES5
  • extract common code
  • Template precompilation
  • Extract the component's CSS
  • Optimize SourceMap
  • Build result output analysis
  • Compilation optimization for Vue projects

(3) Optimization of basic Web technology

  • Enable gzip compression
  • browser cache
  • Use of CDNs
  • Find performance bottlenecks with Chrome Performance

29. Do you know anything about the upcoming vue3.0 features?

Vue 3.0 is on the way to release. The goal of Vue 3.0 is to make the Vue core smaller, faster, and more powerful. Therefore, Vue 3.0 adds the following new features: (1) Changes in the monitoring mechanism 3.0 will bring proxy-based An observer implementation of Proxy that provides reactivity tracking with full language coverage. This removes many of the limitations of the Object.defineProperty based implementation in Vue 2:

  • Can only monitor attributes, not objects
  • Detect addition and deletion of attributes;
  • Detect changes in array index and length;
  • Supports Map, Set, WeakMap, and WeakSet.

The new observer also provides the following features:

  • Public API for creating observables. This provides a simple and lightweight cross-component state management solution for small and medium-scale scenarios.
  • Lazy observation is used by default. In 2.x, no matter how large the reactive data is, it will be observed on startup. If your dataset is large, this can introduce a noticeable overhead at app startup. In 3.x, only the data used to render the initially visible part of the application is observed.
  • More precise change notifications. In 2.x, forcing a new property via Vue.set will cause watchers that depend on that object to be notified of the change. In 3.x, only watchers that depend on a particular property will be notified.
  • Immutable observables: We can create "immutable" versions of values ​​(even nested properties), unless the system temporarily "unblocks" them internally. This mechanism can be used to freeze prop passing or changes outside of the Vuex state tree.
  • Better debugging: We can track exactly when and why a component re-renders using the new renderTracked and renderTriggered hooks.

(2) There is no major change in the template template, only the scope slot is changed. The 2.x mechanism causes the scope slot to change, and the parent component will be re-rendered, while 3.0 changes the scope slot to a function way, which only affects the re-rendering of subcomponents, improving rendering performance. At the same time, for the aspect of the render function, vue3.0 will also make a series of changes to facilitate the habit of directly using the api to generate vdom. (3) Object-based component declaration method Components in vue2.x pass in a series of options through declaration, and the combination with TypeScript needs to be done through some decorators. Although it can realize the function, it is more troublesome. In 3.0, the declaration method of components has been modified and changed to a class-style writing method, which makes it easy to combine with TypeScript. In addition, the source code of vue is also written in TypeScript. In fact, when the functions of the code are complex, there must be a static type system to do some auxiliary management. Now vue3.0 has also been fully rewritten with TypeScript, which makes it easier to combine TypeScript with externally exposed APIs. A static type system is really necessary for the maintenance of complex code. (4) Changes in other aspects The changes in vue3.0 are comprehensive, the above only involves the main three aspects, and there are some other changes:

  • Support custom renderer, so that weex can be extended by custom renderer, instead of directly changing the fork source code.
  • Supports Fragment (multiple root nodes) and Portal (rendering component content in other parts of dom) components, and handles some special scenarios.
  • Based on treeshaking optimization, it provides more built-in functions.

Dachang interview questions share interview question bank

Front-end and back-end interview question banks (necessary for interviews) Recommended: ★★★★★

Address: front-end interview question bank   web front-end interview question bank VS java back-end interview question bank Daquan

Guess you like

Origin blog.csdn.net/weixin_42981560/article/details/130859956