Front-end interview questions—vue articles

Front-end interview notes - vue

Preface

Here are some questions about Vue interviews. I have compiled some frequently asked questions, questions that appear more frequently, and questions that I have personally experienced. If there are any deficiencies, please point them out. We are continuing to update... (ps: one to three ⭐ represents importance, ⭐selective understanding, ⭐⭐mastery, ⭐⭐⭐knowledge that the front-end needs to know)
Insert image description here

1. Principle of two-way data binding ⭐⭐⭐

Answer: Through data hijacking combined with publish-subscribe mode, define get and set methods for each property through Object.defineProperty(), publish messages to subscribers when data changes, and trigger corresponding event callbacks.

2. VUE life cycle⭐⭐⭐

Concept: A series of processes from creation, initializing data, compiling templates, mounting DOM, rendering-update-rendering, uninstallation, etc. are called the life cycle of a Vue instance.

view2.0

  • beforeCreate : before creation. At this time, the component instance has just been created, data observation and event configuration have not yet been performed, and no data can be obtained.
  • created : Creation completed. The vue instance has completed data observation, calculation of attributes and methods ( such as props, methods, data, computed and watch have been obtained at this time ). It is not mounted to the DOM and cannot access the el attribute. The el attribute and the ref attribute content are: Empty arrays are often used for simple ajax requests and page initialization.
  • beforeMount : before mounting. The hang is called before starting and the relevant render function is called for the first time (virtual DOM). Compile the template, generate html from the data in the data and the template, and complete the initialization of el and data. Note that the html is not attached to the page at this time .
  • mounted : Mounting completed. That is, the HTML in the template is rendered into the HTML page. At this time, the DOM node can be obtained through the DOM API. The $ref attribute can be accessed and is often used to obtain VNode information and operations. Ajax requests and mounted will only be executed once.
  • beforeUpdate : Called before the data is updated, it occurs before the virtual DOM is re-rendered and patched, and no additional re-rendering process is triggered.
  • updated : After updated. Called after the virtual DOM is re-rendered and patched due to data changes,
  • beforeDestroy ; before destruction. Called before the instance is destroyed, the instance is still fully available. (Generally, some reset operations are done in this step, such as clearing the timer and monitored DOM events in the component)
  • destroyed : After destruction. Called after the instance is destroyed. After the call, everything indicated by the vue real column will be unbound and all event listeners will be removed.
    Others:
    activated : called when the keep-alive component is activated
    deactivated : called when the keep-alive component is deactivated.
    For details, see the vue2.0 official website life cycle hook

view3.0

  • onBeforeMount
  • onMounted
  • onBeforeUpdate
  • onUpdated
  • onBeforeUnmount
  • onUnmounted

Please add image description
For details, please see vue3.0 official website life cycle hook

3. How to transfer values ​​between components ⭐⭐⭐

1. Transferring values ​​between Vue parent and child components

  • Child components receive data through props and $emittrigger custom events of the parent component;

2. Value transfer between sibling components

  • Build a public component bus.js. The delivery side is triggered by events bus.$emit. The receiver is triggered in the mounted(){} life cycle bus.$on.

3. You can pass parameters across components through VUEX.

4. Value passed down from father to grandson $attrs(down) $listeners(up)

5. Value inheritance from ancestors and descendantsprovide/inject

6. To obtain this.$parent
the details of the parent component instance, please see the parameter passing method of the vue component.

4. The role and implementation principle of v-model⭐⭐

Function: v-model is essentially just syntactic sugar. You can use the v-model directive to create two-way data binding on forms and elements.

Implementation principle:
v-bind: bind responsive data,
trigger oninput events and transfer data

5. Talk about VUEX⭐⭐

Principle: Vuex is a state management tool specially designed for vue.js applications.
constitute:

  • state : basic data of vuex, used to store variables, and the stored data is responsive.
  • mutations : Submit changed data and update status synchronously.
  • actions : Submit mutations, which can be operated asynchronously.
  • getters : are computed properties of the store.
  • modules : Modules, each module has four attributes.
    Regarding how to use VUEX, you can see the value passing problem of VUE.

6. How to solve the problem of data loss when refreshing the VUEX page? ⭐⭐

Reason: Because the data in vuex is stored in the running memory , when the page is refreshed, the page will reload the vue instance, and the data in vuex will be cleared.

Solution: Save the data in vuex directly to the browser cache.

Another way: use a plugin vuex-persistedstate.
vuex-persistedstate can persist the state of the Vuex store into the browser's localStorage or sessionStorage, so that the user can continue to use the previous application state the next time he opens the page.

7.What is the difference between computed and watch? ⭐⭐⭐

The computed value is cached, and the trigger condition is a change in the dependent value. Watch has no cache and supports asynchronous, monitoring data changes.

computed : It is a computed attribute that depends on other attribute values, and the computed value is cached. Only the attribute value it depends on changes, and the computed value will be recalculated the next time the computed value is obtained; watch: more
for observation Function, supports asynchronous, similar to the monitoring callback of certain data. Whenever the monitored data changes, the callback will be executed for subsequent operations;

Computed application scenario: When numerical calculations are required and depend on other data, computed should be used, because the cache feature of computed can be used to avoid recalculation every time the value is obtained; watch application scenario: It needs to be executed when the
data changes Watch should be used for asynchronous or expensive operations. Using the watch option allows us to perform an asynchronous operation (access an API), limit how often we perform the operation, and set intermediate states before we get the final result. These are things that computed properties cannot do.

For details, please see the difference between Vue’s calculated properties, methods, and watches.

8. How to encapsulate axios?

Based on the actual situation of your own project, this article is well written. You can take a look at the simple encapsulation of axios in Vue.

9.The difference between Route and router⭐

  • route : is a routing information object, including "path, parms, hash, name" and other routing information parameters.
  • Router : It is a routing instance object, including routing jump methods, hook functions, etc.

10.The difference between v-show and v-if⭐⭐

  • v-if : Destruction and reconstruction of components, more suitable for operations with permissions, switch to high. If the start condition is false, nothing will be done, and it will compile only if it is true.
  • v-show : css switching, hiding and displaying is more suitable for frequent switching. In any case it will be compiled, then cached, and the DOM elements will be preserved. (v-show = false means display: none; true means display)

11.How to solve the problem that the data in Vue has changed but the view is not up to date?

reason:

  • Array data changes: Use certain methods to operate arrays. When changing data, some methods cannot be monitored by Vue, or the length of the array changes.
    (push(), pop(), shift(), unshift(), splice(), sort(), reverse()) will not change the original array, but return a new array, and the view will not be updated automatically.
  • Vue cannot detect the addition or removal of object properties.
  • Asynchronous update queue: The data is obtained and rendered for the first time, but after the second time, the data is only updated when the page is rendered again, and cannot be updated in real time.

Solution: Array length changes can be modified with splice. If you need to monitor changes in a certain attribute, use $set.

12.Why is data in Vue a function instead of an object? ⭐⭐

There is such an introduction on the official website. For details, you can see the reuse of components. This means that components can be reused
Insert image description here
in Vue , and when data is a function, the data of each instance is independent and will not interact with each other. influence.

A more detailed explanation ==>
Please add image description

13. In VUE, when parent-child components pass values, the parent component requests asynchronously, and the child components cannot be updated in real time. How to solve the problem? (How to solve the problem that the data in VUE cannot be updated in real time?) ⭐⭐⭐

First understand the execution order of the parent and child component life cycles ==>
Load rendering data process
Parent component beforeCreate -->
Parent component created -->
Parent component beforeMount -->
Child component beforeCreate -->
Child component created -->
Child component beforeMount -- >
Subcomponent mounted -->
Parent component mounted -->
Reason: Because the life cycle will only be executed once, the data cannot be obtained until an asynchronous request is made, so when the mounted hook of the subcomponent is executed, the parent component has not yet been obtained. The data is passed, but the result must be printed. In this case, the default value in props can only be printed, the empty string, so the printed result is an empty string.
Solution:

  1. Use v-if to control the timing of component rendering.
    When the asynchronous data of the back-end interface has not been obtained initially, the component will not be rendered, and the component will be rendered again when it is obtained. Use v-if="variable" to control, and initially set this variable to false. In this case, the subcomponent will not be rendered. When the data is obtained, set this variable to true. For example
    :
  data() {
    
    
    return {
    
    
      isTrue:false // 初始为false
    };
  },
  monted(){
    
    
  this.$post.a.b.c.getData(res=>{
    
    
        if(res.result){
    
    
            this.isTrue = true
         }
     })
  }
  1. Use watch to monitor data changes
    . Example:
  props: {
    
    
    tableData: {
    
    
      type: Array,
      default: [],
    },
  },
  watch: {
    
    
     tableData(val){
    
    
         console.log(val)
     }
  },
  1. Using VueX

14. How to pass multiple parameters to parent-child component emit?

Subassembly:

submit(){
    
    
	this.$emit('g',1,2,3,4,5)
}

parent component

g(val1,val2,val3,val4,val5) {
    
    
	console.log(val1,val2,val3,val4,val5)
}

15.VUE routing jump method⭐⭐

  • router-link label jump
  • this.$router.push()
  • this.$router.replace()
  • this.$router.go(n) : (0: current page, -1 previous page, +1 next page, n represents an integer)

16. Conditional rendering v-if and v-for priority ⭐

The vue2.0 document says this:
Insert image description here
vue2 list rendering guide

The vue3.0 document says this about
Insert image description here
vue3 conditional rendering

17. What is the function and principle of $nextTick in VUE? ⭐⭐⭐

Asynchronous rendering, obtaining DOM, Promise, etc.

Vue executes asynchronously when updating the DOM . After modifying the data, the view will not be updated immediately. Instead, the view will be updated uniformly after all data changes in the same event loop are completed. So after modifying the data, immediately obtain the DOM in the method, and the obtained DOM is still the unmodified DOM.
The function of $nextTick is: the code in this method will be executed after the current rendering is completed, which solves the problem of asynchronous rendering not being able to obtain the updated DOM.
The principle of $nextTick: The essence of $nextTick is to return a Promise.

Application scenarios:

  • In created(), if you want to obtain and operate the DOM, put the method of operating the DOM in $nextTick.
  • After the modification in data(), the modified data of data cannot be obtained in the page. When using $nextTick, when the data in data is modified, the page can be rendered in real time.

This is what the official website says
Insert image description here

18.Why does the for loop in VUE add a key? ⭐⭐

Optimize the diff algorithm for performance optimization. Because Vue is a virtual DOM, the diff algorithm is used to compare nodes one by one when updating the DOM. For example, if there are many li elements, a li element needs to be inserted at a certain position, but no key is added to li. , then during operation, all li elements will be re-rendered, but if there is a key, then it will compare the li elements one by one according to the key. You only need to create a new li element and insert it. No need Modify and re-render other elements.
The key cannot be the index of the li element, because if we insert a new element in front of the array, its subscript is 0, then it is repeated with the original first element, and the key of the entire array has changed, so it is the same as The situation is the same without the key.

19.What is the difference between VUE2 and VUE3? ⭐⭐⭐

  • The two-way data binding principle is different.
    Vue2's two-way data binding is implemented by using Object.definePropert() to hijack data and combining it with the publish-subscribe mode.
    Vue3 uses Proxy API to proxy data.
  • API types are different
    Vue2 uses option type api.
    Vue3 uses synthetic API.
  • Different from defining data variables and methods,
    Vue2 puts the data in data.
    Vue3 needs to use a new setup() method.
  • different life cycles
  • Father and son pass on different parameters
  • Instructions are different from slots
  • Whether to support fragmentation
    Vue2 does not support fragmentation.
    Vue3 supports fragmentation and can have multiple root nodes

20.Why doesn’t VUE3 continue to use $set?

The role of $set : In vue2.0: use objects and arrays to define data. When you need to add a property or element to an object or array, and want it to update responsively when updating the View, you need to use $set method to complete.
Vue2 uses object.definedProperty to implement data response and cannot monitor changes in deep data .

Proxy is used in Vue3 to proxy the data through ref and reactive to change the value and object type into responsive objects, so that modifications and additions to it can be captured by Vue, thereby realizing automatic refresh of the page.
view2
view 3

Refer to the official website responsive basics

21.The difference between history and hash in VUE routing⭐⭐

  • Address bar with or without "#"
    hash: http://localhost:8080/#/
    history:http://localhost:8080/

  • They all use two features of the browser to implement front-end routing.
    History uses the API of the browsing history stack to implement
    hashing, which is implemented by monitoring the hash value change events of the location object.

  • The same URL
    history will be triggered to be added to the browser history stack. Hash will not be triggered.
    History requires the cooperation of the backend. If the backend does not cooperate with refreshing the page, 404 will appear . Hash is not required.

Principle of hashRouter : Obtain the hash value in the URL through window.onhashchange
Principle of historyRouter : Through history.pushState , using it to jump to the page will not trigger a page refresh. Use window.onpopstate to monitor the browser's forward and backward movements.

Insert image description here
Insert image description here
For details, please see the official website for different historical modes | Vue Router

22.The difference between Pinia and Vuex⭐

  • Support option API and combined API
  • Pinia has no mutations, only state, getters, and actions.
  • pinia sub-module does not require modules
  • Support TypeScript
  • Automated code splitting
  • Pinia is smaller
  • pinia can directly modify state data

Reference https://github.com/vuejs/rfcs/pull/271

23.Vue Diff algorithm⭐

When a component is created and updated, Vue will execute the internal update function. This function uses the render function to generate a virtual DOM tree, compares the old and new trees, finds the differences, and finally updates the real DOM.

The process of comparing differences is called diff , and Vue completes this process internally through a function called patch.

When comparing, Vue uses depth priority and same-layer comparison for comparison .

When comparing whether two nodes are the same, Vue makes a judgment based on the key and tag of the virtual node.

First, compare the root node. If they are the same, mount the reference of the real dom associated with the old node to the new node, then update the attributes to the real dom as needed, and then compare its child node arrays. If they are not the same, then use the new node as the reference. The information recursively creates all real DOM, mounts it to the corresponding virtual node at the same time, and then removes the old DOM.

When comparing its child node arrays, Vue uses two pointers for each child node array. Point to the head and tail respectively, and then keep moving closer to the middle for comparison. The purpose is to reuse the real DOM as much as possible and create and destroy the real DOM as little as possible. If they are found to be the same, enter the same comparison process as the root node. If they are different, move the real DOM to the appropriate position.

This recursive traversal continues until the entire tree is compared.

Optimization strategies in Vue
Some optimization strategies are introduced in Vue's diff algorithm to reduce unnecessary diff operations and improve diff performance. Specifically, the following points are:

  • Static node marking during template compilation.
    When Vue compiles a template, it will mark those static nodes that do not need to be changed, so that in subsequent rendering, the diff operation on these nodes can be omitted, reducing the complexity of diff and improving performance.
  • Key value optimization for list traversal
    In Vue, when traversing a list, we usually specify a key value for each child element to uniquely identify them to facilitate subsequent diff operations. During this process, Vue will record the key value to compare whether the old and new nodes have changed. If there is no change, the corresponding state of the node will be retained to avoid unnecessary repeated rendering.
  • Merge optimization of the same nodes
    In the diff algorithm, if the old and new nodes are the same node (that is, both nodes have the same labels and attributes), and neither child node needs to be updated, the two nodes are considered to be the same and can be directly Skip the diff operation on this node to improve diff performance.

Vue's diff algorithm is an efficient front-end responsive implementation that can quickly compare the differences between old and new nodes and quickly update the page view, improving user experience and program performance.

24. Dynamic components & asynchronous components⭐

Dynamic components and asynchronous components are both designed to achieve dynamic rendering and on-demand loading of components, which can improve application performance and flexibility.
Dynamic components : When rendering components, dynamically select components based on certain conditions.
Insert image description here
Asynchronous components : The loading and rendering process of components is divided into two parts, that is, the code and dependencies of the component are loaded first, and then they are rendered to the page after the loading is successful. This avoids loading the code and dependencies of all components at once during the initial load, thereby improving the performance and responsiveness of the page. In Vue, you can use factory functions and the asynchronous loading feature of components to implement asynchronous component loading.
Refer to the official website
vue2 asynchronous component
vue3 asynchronous component

25. Event modifiers⭐

.stop : Prevent the click event from continuing to propagate
. prevent : Submit the event and no longer reload the page
. capture : Use the event capture mode when adding an event listener.
self : The handler function is triggered when the current element itself. once
: It will only be triggered once
. passive :Improve the performance of mobile terminal.

<!-- 阻止单击事件继续传播 -->
<a v-on:click.stop="doThis"></a>

<!-- 提交事件不再重载页面 -->
<form v-on:submit.prevent="onSubmit"></form>

<!-- 修饰符可以串联 -->
<a v-on:click.stop.prevent="doThat"></a>

<!-- 只有修饰符 -->
<form v-on:submit.prevent></form>

<!-- 添加事件监听器时使用事件捕获模式 -->
<!-- 即内部元素触发的事件先在此处理,然后才交由内部元素进行处理 -->
<div v-on:click.capture="doThis">...</div>

<!-- 只当在 event.target 是当前元素自身时触发处理函数 -->
<!-- 即事件不是从内部元素触发的 -->
<div v-on:click.self="doThat">...</div>

<!-- 点击事件将只会触发一次 -->
<a v-on:click.once="doThis"></a>

<!-- 滚动事件的默认行为 (即滚动行为) 将会立即触发 -->
<!-- 而不会等待 `onScroll` 完成  -->
<!-- 这其中包含 `event.preventDefault()` 的情况 -->
<div v-on:scroll.passive="onScroll">...</div>
 

For details, please see the official website event modifiers

26. How to transfer parameters between routes⭐

  • Navigation jump delivery via router-link
<router-link to=`/a/${
      
      id}`>routerlink传参</router-link>
  • Use the push method to splice and carry parameters when jumping.
  this.$router.push({
    
    
          path: `/getlist/${
      
      id}`,
        })
  • Determine the matching route through the name in the routing attribute, and pass the parameters through params.
this.$router.push({
    
    
          name: 'Getlist',
          params: {
    
    
            id: id
          }
        })
  • Use path to match routes, and then pass parameters through query.
this.$router.push({
    
    
          path: '/getlist',
          query: {
    
    
            id: id
          }
        })

Note: query is a bit like a get request in ajax , and params is like a post request.

params does not display parameters in the address bar, refresh the page, the parameters are lost,
other methods display the passed parameters in the address bar, refresh the page, the parameters are not lost.

For details, please see Vue-router's three simple routing parameter passing methods.

other

For other front-end interview questions, you can read this

Front-end interview questions (with answers) are being improved...

Guess you like

Origin blog.csdn.net/Jet_Lover/article/details/130706432