Home  >  Article  >  Web Front-end  >  Summary of common Vue interview questions (with answer analysis)

Summary of common Vue interview questions (with answer analysis)

青灯夜游
青灯夜游forward
2021-04-08 19:54:1714336browse

This article will share with you some Vue interview questions (with answer analysis). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

The information involved in the article comes from the Internet and personal summary. It is intended to summarize personal learning and experience. If there is any infringement, please contact me to delete it. Thank you. !

1. Understanding MVVM

MVVM is the abbreviation of Model-View-ViewModel.

Model represents the data model, and business logic for data modification and operation can also be defined in the Model.

View represents the UI component, which is responsible for converting the data model into UI for display.

ViewModel Monitors changes in model data, controls view behavior, and handles user interaction. A simple understanding is an object that synchronizes View and Model, connecting Model and View.

Under the MVVM architecture, there is no direct connection between View and Model. Instead, they interact through ViewModel. The interaction between Model and ViewModel is two-way, so changes in View data will be synchronized to the Model. , and changes in Model data will be immediately reflected on the View.

ViewModel The View layer and Model layer are connected through two-way data binding, and the synchronization between View and Model is completely automatic without human intervention, so developers only need You need to pay attention to business logic, do not need to manually operate the DOM, and do not need to pay attention to the synchronization of data status. Complex data status maintenance is completely managed by MVVM.

2. Vue implements two-way data binding

Vue implements two-way data binding mainly by: using data hijacking combined with the publisher-subscriber model method, through Object.defineProperty() to hijack the setters and getters of each property, publish messages to subscribers when the data changes, and trigger the corresponding listening callbacks. When you pass a plain Javascript object to a Vue instance as its data option, Vue will iterate through its properties and convert them into getters/setters using Object.defineProperty. The getters/setters are not visible to the user, but internally they allow Vue to track dependencies and notify changes when properties are accessed and modified. (Learning video sharing: vue video tutorial)

Vue’s two-way data binding uses MVVM as the entrance to data binding, integrates Observer, Compile and Watcher, and monitors itself through Observer For model data changes, Compile is used to parse the compilation template instructions (in vue, it is used to parse {{}}), and finally the watcher is used to build a communication bridge between the observer and Compile to achieve data changes -> View Update; view interactive change (input) -> data model change two-way binding effect.

3. Parameter transfer between Vue components

1. Value transfer between parent component and child component

Transfer from parent component To child components: child components receive data through props method; child components pass to parent components: $emit method passes parameters

2. Data transfer between non-parent and child components, sibling components pass values

eventBus is to create an event center, which is equivalent to a transfer station, and can be used to deliver and receive events. If the project is relatively small, this is more appropriate.

4. The difference between v-show and v-if

  • The difference between v-show and v-if:

    v-show is a css switch, v-if is a complete destruction and re-creation.

  • Use

    Use v-show when switching frequently, use v-if when there are few changes during runtime

  • v -if='false' v-if is conditional rendering, it will not render when false

5, Vue life cycle

beforeCreate (Before creation) Before data observation and initialization events have started

created (After creation) Complete data observation, operation of properties and methods, initialization events, The $el attribute has not yet been displayed

beforeMount (before loading) is called before the mount starts, and the related render function is called for the first time. The instance has completed the following configuration: compile the template, and generate html from the data in the data and the template. Note that the html has not been mounted on the page at this time.

mounted (after loading) Called after el is replaced by the newly created vm.$el and mounted to the instance. The instance has completed the following configuration: replace the DOM object pointed to by the el attribute with the compiled html content above. Complete the rendering of the html in the template into the html page. Ajax interaction is performed during this process.

beforeUpdate (before update) Called before the data is updated, which occurs before the virtual DOM is re-rendered and patched. You can further change the state in this hook without triggering an additional re-rendering process.

updated(Updated) Called after virtual DOM re-rendering and patching due to data changes. When called, the component DOM has been updated, so DOM-dependent operations can be performed. In most cases, however, changing state during this period should be avoided, as this may cause an infinite loop of updates. This hook is not called during server-side rendering.

beforeDestroy (before destruction) Called before the instance is destroyed. The instance is still fully available.

destroyed (after destruction) Called after the instance is destroyed. After calling, all event listeners will be removed and all child instances will be destroyed. This hook is not called during server-side rendering.

1. What is the vue life cycle?

Answer: The process from creation to destruction of a Vue instance is the life cycle. A series of processes from starting to create, initializing data, compiling templates, mounting Dom→rendering, updating→rendering, and destruction are called the life cycle of Vue.

2.What is the role of vue life cycle?

Answer: There are multiple event hooks in its life cycle, making it easier for us to form good logic when controlling the process of the entire Vue instance.

3. How many stages are there in the vue life cycle?

Answer: It can be divided into 8 stages in total: before/after creation, before/after loading, before/after update, before/after destruction.

4. Which hooks will be triggered when the page is loaded for the first time?

Answer: The following beforeCreate, created, beforeMount, mounted will be triggered.

5. In which cycle is DOM rendering completed?

Answer: DOM rendering is completed in mounted.

5. Array usage of bound class

  • Object methodv-bind:class="{'orange': isRipe, 'green ': isNotRipe}"
  • Array methodv-bind:class="[class1, class2]"
  • Inlinev-bind:style ="{color: color, fontSize: fontSize 'px' }"

6. The difference between computed attribute computed and monitoring watch

Computed Properties automatically monitor changes in dependent values ​​and dynamically return content. Monitoring is a process. When the monitored value changes, a callback can be triggered and something done. So the difference comes from the usage. If you just need dynamic values, then use calculated properties; if you need to know the value changes and then execute the business logic, use watch. Although it is possible to use reverse or mixed methods, they are incorrect usages.

1. When computed is an object, what options does it have?

There are two options: get and set

2. What is the difference between computed and methods?

methods is a method, it can accept parameters, but computed cannot. Computed can be cached, but methods cannot

3. Can computed rely on data from other components?

computed can depend on other computed, even the data of other components

4. When watch is an object, what options does it have?

handler deep Whether to be deep immeditate Whether to execute immediately

Summary

When some data needs to change with other data, it is recommended to use computed. When there is a general response to data changes, it is recommended to use watcher when performing some business logic or asynchronous operations

7. Vue’s routing implementation: hash mode and history mode

hash mode: In the browser, the symbol "#", # and the characters after # are called hash, and are read with window.location.hash; Features: Although the hash is in the URL, But it is not included in the HTTP request; it is used to guide browser actions and is useless for server-side security. The hash will not reload the page. In hash mode, only the content before the hash symbol will be included in the request, such as http://www.xxx.com. Therefore, for the backend, even if full coverage of the route is not achieved, 404 will not be returned. mistake.

history mode: history adopts the new features of HTML5; and provides two new methods: pushState(), replaceState() to modify the browser history stack, and the popState event to monitor status changes. In history mode, the URL of the front end must be consistent with the URL that actually initiates the request to the back end, such as http://www.xxx.com/items/id. If the backend lacks routing processing for /items/id, a 404 error will be returned.

8. What is the difference between Vue, Angular and React?

(The version is constantly updated, the following differences may not be very correct. I only use vue in my work, and I am not very familiar with angular and react)

1. Differences from AngularJS

Same points:

Both support instructions: built-in instructions and custom instructions; both support filters: built-in filters and custom filters; both support two-way data binding; none support low-end browsers.

Differences:

AngularJS has a high learning cost, such as the addition of the Dependency Injection feature, while the APIs provided by Vue.js itself are relatively simple and intuitive; in terms of performance AngularJS relies on dirty checking of data, so the more Watchers, the slower it is; Vue.js uses observation based on dependency tracking and uses asynchronous queue updates, and all data is triggered independently.

2. Differences from React

Same points:

React uses special JSX Grammar, Vue.js also recommends writing .vue special file format in component development. There are some conventions on file content. Both need to be compiled and used; the central idea is the same: everything is a component, and component instances can be nested. ; both provide reasonable hook functions that allow developers to customize their needs; neither have built-in AJAX, Route and other functions into the core package, but are loaded as plug-ins; both support the features of mixins in component development .

Differences:

The Virtual DOM used by React will perform dirty checks on the rendered results; Vue.js provides instructions, filters, etc. in the template. You can operate Virtual DOM very conveniently and quickly.

9. Event modifier

  • Bind a native click event: add native,

  • Other event modifiers: stop prevent self

  • Key combination: click.ctrl.exact is only triggered when ctrl is pressed

10. Why is the data in the component a function?

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

Because components are used for reuse, objects in JS are reference relationships, so the scope is not isolated, and instances of new Vue will not be reused, so there is no problem of referencing objects

Understanding that Vue is a progressive framework

11. The meaning of progressive is: the least assertion.

Vue may not be as good as React or Angular in some aspects, but it is progressive and has no strong claims. You can use it to implement one or two components on top of the original large system. Use it with jQuery; you can also use it to develop the whole family bucket and use it as Angular; you can also use its view to match the entire lower layer of your own design. You can use the concepts of OO and design patterns in the underlying data logic, or you can use functional methods. It is just a lightweight view. It only does what it should do and does not do anything it shouldn't do. , nothing more. My understanding of the meaning of progressive is: not doing more than what is required.

12. What are the two cores of vue.js?

Data-driven and componentized

13. The role of key value in vue

Use key to The purpose of creating a unique identifier

key for each node is mainly to update the virtual DOM efficiently. In addition, when using transition switching of elements with the same tag name in Vue, the key attribute will also be used. The purpose is also to allow Vue to distinguish them. Otherwise, Vue will only replace its internal attributes and not trigger the transition effect.

14. The priority of v-for and v-if

The priority of v-for is higher than v-if

15. Component

1. How to call parent component in vue by sub-component

The first method is to pass this.$parent directly in the sub-component .event to call the parent component's method.

The second method is to use $emit in the child component to trigger an event to the parent component, and the parent component can listen to this event.

The third method is that the parent component passes the method to the child component and calls this method directly in the child component.

2. The parent component in vue calls the method of the child component

The parent component uses the ref attribute to operate the child component method.

父:
<child ref="childMethod"></child>
子:
method: {
  test() {
     alert(1)
  }
}
在父组件里调用test即 this.$refs.childMethod.test()

3. Passing values ​​between vue components

(1) Parent component passes value to child component:

  • Dynamically bind properties when the parent component calls the child component

<parent :dataList=&#39;dataList&#39;></parent>
  • The child component defines props to receive dynamically bound property props: ['dataList']

  • Sub-component usage data

(2) Sub-component actively obtains the properties and methods between parent and child:

Use this.$parent.property/this.$parent.method in child components.

(3) The child component passes the value to the parent component:

1. Use the ref attribute
1. Bind the attribute ref when the parent component calls the child component
< ;parent :ref='parent'>
2. Use this.$refs.parent.property/this.$refs.parent.method in the parent component
2. Use $emit Method
1. The child component calls this.$emit('method name', pass value)
2. The parent component obtains the passed value through the 'method name' bound to the child component.

(4) Value transfer between vue page-level components

  • Use vue-router to pass parameters with parameters through jump links.

  • 使用本地缓存localStorge。

  • 使用vuex数据管理传值。

(5)说说vue的动态组件。

多个组件通过同一个挂载点进行组件的切换,is的值是哪个组件的名称,那么页面就会显示哪个组件。

(6)keep-alive内置组件的作用

可以让当前组件或者路由不经历创建和销毁,而是进行缓存,凡是被keep-alive组件包裹的组件,除了第一次以外。不会经历创建和销毁阶段的。第一次创建后就会缓存到缓存当

(7)递归组件的用法

组件是可以在它们自己的模板中调用自身的。不过它们只能通过 name 选项来做这件事。首先我们要知道,既然是递归组件,那么一定要有一个结束的条件,否则就会使用组件循环引用,最终出现“max stack size exceeded”的错误,也就是栈溢出。那么,我们可以使用v-if="false"作为递归组件的结束条件。当遇到v-if为false时,组件将不会再进行渲染。

16、怎么定义vue-router的动态路由?怎么获取传过来的值?

动态路由的创建,主要是使用path属性过程中,使用动态路径参数,以冒号开头,如下:

{
 path: &#39;/details/:id&#39;
 name: &#39;Details&#39;
 components: Details
}

访问details目录下的所有文件,如果details/a,details/b等,都会映射到Details组件上。

当匹配到/details下的路由时,参数值会被设置到this.$route.params下,所以通过这个属性可以获取动态参数

this.$route.params.id

17、vue-router有哪几种路由守卫?

全局守卫:beforeEach
后置守卫:afterEach
全局解析守卫:beforeResolve
路由独享守卫:beforeEnter

18、$route和 $router的区别是什么?

  • $router为VueRouter的实例,是一个全局路由对象,包含了路由跳转的方法、钩子函数等。

  • $route 是路由信息对象||跳转的路由对象,每一个路由都会有一个route对象,是一个局部对象,包含path,params,hash,query,fullPath,matched,name等路由信息参数。

19、vue-router响应路由参数的变化

  • (1)用watch 检测

  • (2)组件内导航钩子函数

20、 vue-router 传参

(1)使用Params:
  • 只能使用name,不能使用path

  • 参数不会显示在路径上

  • 浏览器强制刷新参数会被清空

(2)使用Query:
  • 参数会显示在路径上,刷新不会被清空

  • name 可以使用path路径

21、不用Vuex会带来什么问题?

1、可维护性会下降,你要想修改数据,你得维护三个地方

2、可读性会下降,因为一个组件里的数据,你根本就看不出来是从哪来的

3、增加耦合,大量的上传派发,会让耦合性大大的增加,本来Vue用Component就是为了减少耦合,现在这么用,和组件化的初衷相背。

22、vuex有哪几种属性?

有五种,分别是 State、 Getter、Mutation 、Action、 Module。

23、、vuex的State特性是?

1、Vuex就是一个仓库,仓库里面放了很多对象。其中state就是数据源存放地,对应于与一般Vue对象里面的data
2、state里面存放的数据是响应式的,Vue组件从store中读取数据,若是store中的数据发生改变,依赖这个数据的组件也会发生更新
3、它通过mapState把全局的 state 和 getters 映射到当前组件的 computed 计算属性中

24、vuex的Getter特性是?

1、getters 可以对State进行计算操作,它就是Store的计算属性
2、 虽然在组件内也可以做计算属性,但是getters 可以在多组件之间复用
3、 如果一个状态只在一个组件内使用,是可以不用getters

25、vuex的Mutation特性是?

1、Action 类似于 mutation,不同在于:
2、Action 提交的是 mutation,而不是直接变更状态。
3、Action 可以包含任意异步操作

26. Should the ajax request code in Vue.js be written in the methods of the component or in the actions of vuex?

1. If the requested data is to be shared by other components and is only used within the requested component, there is no need to put it in the state of vuex.

2. If it is reused elsewhere, this is most likely needed. If necessary, please put the request into the action to facilitate reuse, and package it into a promise to return, and use async at the call site. await processes the returned data. If you do not want to reuse this request, it is very convenient to write it directly in the vue file.

27, vue two-way data binding principle, the difference between vue2 and vue3 principles

Because vue2.0 object.defineProperty It can only hijack object attributes and cannot monitor changes in array subscripts, resulting in the disadvantage that elements added through data subscripts cannot respond in real time. In order to solve this problem, after Vue internal processing, you can use push(), pop(), shift(), unshift(), splice(), sort(), reverse() for hack processing, so other array attributes are also monitored No, it has certain limitations.

Because object.defineProperty can only hijack object properties, each property of each object needs to be traversed. In vue2.0, data monitoring is achieved by recursively traversing the data object. If the attribute value is an object, deep traversal is also required.

The proxy in Vue3.0 can not only proxy objects, but also proxy arrays, and can also proxy dynamically added attributes. There are 13 hijacking operations: get gets a certain key value (receives 2 parameters, target value and target value key value) set sets a key value (target value, target key value, value to be changed, original value before change) apply Use the in operator to determine whether a key exists deleteProperty deletes a property defineProperty definition A new property

Thanks

For more programming-related knowledge, please visit: Programming Video! !

The above is the detailed content of Summary of common Vue interview questions (with answer analysis). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete