Vue interview questions accumulation

Vue interview questions finishing

One, the understanding of mvvm?

mvvm is the abbreviation of Model-View-ViewModel

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

View represents the view layer, representing the UI components, that is, the part of the webpage presented to the user. The hard-coded parts of the webpage will not be dynamically updated with data, and some are updated based on the data. The updated data is obtained from the model layer. It is responsible for transforming the data model into a UI display

ViewModel monitors changes in model data and 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 the View and the Model, but through the ViewModel to interact. The interaction between the Model and the ViewModel is two-way, so the changes in the View data will be synchronized to the Model, and the changes in the Model data It will also be reflected on the View immediately.

ViewModel links the View layer and Model layer through two-way data binding, and the synchronization between View and Model is completely automatic, and there is no need to think of interference. Therefore, developers only need to pay attention to business logic and do not need to manually manipulate the DOM. Concerned about the synchronization of data status, complex data status maintenance is completely managed by MVVM.

Second, the Vue life cycle

beforeCreate : before the data observation and initialization time has not yet started

After created : complete data observation, attribute and method calculations, initialize events, the $el attribute is out without Shina

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

After mounted loaded: Called after el is replaced by the created .vm.$el and mounted on the instance. The example has completed the following configuration: replace the DOM object pointed to by the el attribute with the html content compiled above. Finish rendering the html in the template to the html page. Ajax interaction is carried out in this process.

beforeUpdate : Called before the data is updated, which occurs before the virtual DOM is re-rendered and patched. The state can be further changed in this hook without triggering an additional re-rendering process.

updated : Called after the DOM is re-rendered and patched due to data changes. When called, the component DOM has been updated, so operations that depend on the DOM can be performed. However, in most cases, you should avoid updating the status during this period, as this may cause an endless loop of updates. This dog is not called during server-side rendering.

beforeDestroy : Called before the instance is destroyed. The instance is still fully available.

After destroyed : Called after the instance is destroyed. After the call, all event listeners will be removed and all child instances will be destroyed. This dog is not called during server-side rendering.

1. What is the life cycle?

The process from mounting to destruction of a Vue instance is the life cycle. Create from the beginning, initialize data, compile templates, mount DOM-render, update-render. A series of processes such as destruction are called the life cycle of Vue

2. What is the role of Vue life cycle?

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

3. There are several stages in the Vue life cycle

Eight stages before and after creation, before and after loading, before and after update, before and after destruction

4. Which hooks will be triggered on the first page load

beforeCreate,created,beforeMount,mounted

5. DOM rendering has been completed in which cycle

DOM rendering has been completed in mounted

Three Vue realizes the principle of two-way data binding: Object.defineProperty()

Vue implements two-way data binding mainly: using data hijacking combined with the publisher-subscriber model to hijack the setter and getter of each property, publish messages to subscribers when the data changes, and trigger the corresponding listener callback. When passing a normal Javascript object to a Vue instance as its data option, Vue will traverse its properties and use Object.defineProperty to convert them to getter/setter. Users can't see getters/setters, but internally they let Vue track dependencies and notify changes when properties are accessed and modified.

Vue's two-way data binding uses MVVM as the entry point for data binding, integrating Observer, Compile and Watcher, through Observer to monitor the data changes of your own model, and Compile to parse the compilation template instructions (in vue is used to parse { {}}), finally use the watcher to build a communication bridge between the observer and the Compile to achieve the data change—>view update; view interaction change (input)—>data model change two-way binding effect.

four. Parameter transfer between Vue components.

1. The mutual transfer of values ​​between parent and child components

The parent component is passed to the child component: the child component receives data through the props method;

The child component is passed to the parent component: $emit method passes parameters

2. The brother components pass by value.

eventBus is to create an event center, which is equivalent to a transit station, which can be used to transmit and receive events. It is suitable when the project is relatively small.

5. Vue's routing implementation, hash mode and history mode

Hash mode in the browser symbol "#", # and the characters after # are called hash, read with window.location.hash;

Features: Although the hash is in the URL, 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. For example, for the backend, even if the routing is not fully covered, it will not return a 404 error.

History mode : history adopts the new features of HTML5; and provides two new methods: pushState(), replaceState() can modify the browser history stack, and the popState event listens to state changes. In the history mode, the front-end URL must be consistent with the actual request to the back-end URL, such as: http://www.xxx.com/items/id. If the backend lacks routing processing for /items/id, it will return a 404 error. The Vue-Router official website describes it as follows: "However, this mode needs to be played well and requires back-end configuration support... So, you have to add a candidate resource that covers all situations on the server: if the URL does not match any static resources, It should return the same index.html page, which is the page your app depends on."

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

1. Difference with AngularJS

Similarities: Both support commands: built-in commands and custom commands; both support filters: built-in filters and custom filters; both support two-way data binding; neither support low-end browsers.

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

2. The difference with React

Same point:

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

Differences: The Virtual DOM used by React will perform dirty checks on the rendered results; Vue.js provides instructions, filters, etc. in the template, which can be very convenient and fast to operate the Virtual DOM.

Seven. Hook function of Vue routing

The homepage can control navigation jump, beforeEach, afterEach, etc., which are generally used to modify the page title. Some require login to adjust the redirection function of the page.

beforeEach mainly has three parameters to from, next

to: The target routing object that the route will enter.

from: route the current navigation is about to leave

next: The function must call the method. The effect of the resolve hook depends on the call parameters of the next method. You can control the jump of web pages.

8. What is Vuex? how to use? Which functional scenarios use it?

Vuex is a set of state management tools for Vue.js applications. It uses a centralized management mode to manage the state of all components in the application.

Application scenarios: music playback, login status, add to shopping cart

The core attributes of store in Vuex

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

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

vuex的Mutation特性
改变store中state状态的唯一方法就是提交mutation,就很类似事件。
每个mutation都有一个字符串类型的事件类型和一个回调函数,我们需要改变state的值就要在回调函数中改变。
我们要执行这个回调函数,那么我们需要执行一个相应的调用方法:store.commit。

Action 类似于 mutation,不同在于:Action 提交的是 mutation,而不是直接变更状态;
Action 可以包含任意异步操作,Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,
因此你可以调用 context.commit 提交一个 mutation,
或者通过 context.state 和 context.getters 来获取 state 和 getters。
Action 通过 store.dispatch 方法触发:eg。
store.dispatch('increment')

vuex的module特性
Module其实只是解决了当state中很复杂臃肿的时候,module可以将store分割成模块,
每个模块中拥有自己的state、mutation、action和getter

nine. Understanding of keep-alive

Keep-alive is a built-in component of Vue, which can keep the state of the contained components or avoid re-rendering.

After Vue 2.1.0 version, keep-alive has added two new attributes, include (included component cache) and exclude (excluded component is not cached, priority is greater than include).

Parameter explanation:

include-string or regular expression, only components with matching names will be cached

exclude-string or regular expression, any components with matching names will not be cached

The include and exclude attributes allow the component to be cached conditionally. Both can use "," to separate strings, regular expressions, and arrays. When using regular or array, remember to use v-bind

ten. One sentence interview

CSS only works in the current component.

​ Write scoped in the style tag

The difference between v-if and v-show

v-if renders DOM elements according to conditions, v-show ten display block or none

route sum route sum The difference between r o u t e and router

$route Ten routing information objects include path, params, hash, query fullPath matched name and other routing information parameters,

$router ten routing examples, the object includes routing jump methods, hook functions

What are the two cores of vue.js?

Data-driven component system.

Vue common instructions

v-for v-if v-bind v-on v-show v-else

What modifiers are commonly used in vue?

.prevent will not reload the page after submitting the event; .stop prevents the event from bubbling. self: triggers when the event occurs in the element itself instead of a child element; .capture: the event listener, you can choose the order of bubbling

v-on can bind multiple methods
What is the role of the key value in vue?

When Vue.js uses v-for to update the list of rendered elements, it defaults to the "in-place reuse strategy. If the order of the data items is changed, Vue will not move the DOM elements to match the order of the data items. Instead, simply take each element here and ensure that it displays each element that has been rendered under a specific index. The key is mainly to update the virtual DOM efficiently.

What are the calculated properties of vue

Answer: Putting too much logic in the template will make the template too heavy and difficult to maintain. When the data needs to be processed complexly and may be used multiple times, try to use the method of calculating attributes. Benefits: ①Make the data processing structure clear; ②Depend on data, update the data, and automatically update the processing results; ③The internal this of the calculated attribute points to the vm instance; ④When calling the template, you can directly write the name of the calculated attribute; ⑤Getters are commonly used Method, to obtain data, you can also use the set method to change the data; ⑥Compared with methods, no matter the dependent data changes, the methods will be recalculated, but when the dependent data does not change, computed will get it from the cache and will not be recalculated.

Single page applications such as vue and their advantages and disadvantages

Advantages: Vue's goal is to implement responsive data binding and combined view components through the simplest possible API. The core is a responsive data binding system, MVVM, data-driven, componentized, lightweight, brief introduction, efficient, fast, and module friendly

Disadvantages: does not support low-version browsers, and only supports IE9 at least. It is not conducive to SEO optimization (if you want to support SEO, it is recommended to use server-side rendering components). The first time to load the home page is relatively long; it is impossible to use the browser The navigation buttons need to realize forward and backward by themselves.

How to define the dynamic routing of vue-router? How to get the passed value

In the index.js file in the router directory, add: /id to the path attribute to get it using params.id in the router

Eleven route jump method

1. The router-link label will be rendered as a label, or jump through js such as router.push

12. What is the difference between Computed and watch

computed

Computed is a calculated attribute, that is, a calculated value. It is more used in scenarios where the value is calculated

The computed value is cacheable. The computed value will be cached after the getter is executed. It is only calculated by the getter that is called again when the computed value is obtained next time after the attribute value it depends on changes.

Computed is suitable for computing scenarios that consume more performance.

watch

Watch is more of an observation function, similar to the monitoring callback of some data, used to observe the value of props $emit or this component, and execute the callback for subsequent operations when the data changes

No cache line, will be executed if the value does not change when the page is re-rendered

How to choose:

When we want to perform numerical calculations and rely on other data, then design this data as computed.

If you need to do something when a certain data changes, use watch to observe the data change.

13. The role of scoped attributes in Vue components

Indicates that the style can only be applied to the current module, which well achieves the purpose of style privatization

But it must be used with caution, the style is not easy to modify, and in many cases we need to fine-tune the style of public components

Solution

①: Use mixed css styles: (mix the global and local styles)

Fifteen: The understanding of the progressive framework: advocate at least not doing more than responsibilities

The least assertion means that the requirements for users are relatively low, and there is no more work outside of their duties. Is it equivalent to writing the code according to your needs, without having to manipulate things other than the code too much.
Bottom-up: According to the literal meaning, first write the bottom layer, and then write up layer by layer, just like building a building, lay the foundation, and then start to build the building upwards. Vue is the same from the bottom up. Render, write.

Sixteen: Can v-on monitor multiple methods?

can

Two ways of writing one element bound to multiple events, two ways of writing one event bound to multiple functions, and the use of modifiers.

<a style="cursor:default" v-on='{click:DoSomething,mouseleave:MouseLeave}'>doSomething</a>

Seventeen: Why must the data in the vue component be a function

The value of data in a vue component cannot be an object, because the object is a reference type, and the component may be referenced by multiple instances at the same time. If the data value is an object, it will cause multiple instances to share an object. If one component changes the data attribute value, other instances will also be affected.

Eighteen: the compilation principle of webpack

The role of webpack:

Dependency management: It is convenient to reference third-party modules, making it easier to reuse modules, avoiding conflicts caused by global injection, and avoiding repeated loading or loading of unnecessary modules. It reads dependent modules layer by layer, adds different entries and does not repeatedly package dependent modules.

Merged code: centrally package various scattered modules into large files to reduce the number of http request connections, and cooperate with UglifyJS

**One sentence summary:** The role of webpack is to handle dependencies, modularize, package compressed files, and manage plugins.
Everything is a module. Since webpack only supports js files, it needs to be converted to a module supported by webpack with loader. The plugin is used to expand the functions of webpack. During the process of webpack construction life cycle, do the right things at the right time .

How does webpack work?

①Analyze the configuration parameters, merge the configuration information from the shell (npm install similar command) and webpack.config.js file, and output the final configuration information;
②Register the plug-in in the configuration, let the plug-in listen to the event node in the webpack build life cycle , Make a corresponding response;
③Analyze the entry file in the configuration file, and find out the files that each file depends on, and recurse;
④In the process of recursing each file, look for the file type and loader in the configuration file Output the corresponding loader to convert the file;
⑤After the recursion, the final result of each file is obtained, and the code chunk (the name after packaging) is generated according to the entry configuration;
⑥All the chunks are output to the file system.

Nineteen complete vue-router navigation analysis process

1. Navigation is triggered;
2. Call the beforeRouteLeave guard in the deactivated component;
3. Call the global beforeEach guard;
4. Call the beforeRouteUpdate guard in the reuse component;
5. Call the beforeEnter guard in the routing configuration;
6. Analyze asynchronous Routing component;
7. Call beforeRouteEnter guard in the activated component;
8. Call the global beforeResolve guard;
9. Navigation is confirmed;
10...Call the global afterEach hook;
11. DOM update;
12. Call beforeRouteEnter with the created instance The callback function passed to next in the guard.

Twenty: The difference between params and query

Usage: query should be imported with path, params should be imported with name, the accepted parameters are similar, respectively

this. r o u t e . q u e r y , n a m e 和 t h i s . route.query,name和this. route.query,n a m e and t h i s . route.params.name

URL address: query is similar to get, params is similar to post, the former will not be lost after refreshing, the latter will be lost

Method to trigger view update when Vue updates the array

push() pop() shift() unshift() splice() sort() reverse()

Guess you like

Origin blog.csdn.net/qq_40629046/article/details/109703569