Vue interview questions, the most complete summary

Vue common interview questions

Advantages of vue?

  • Lightweight framework: only focuses on the view layer, which is a collection of views that builds data, with a size of only tens of kb;
  • Simple and easy to learn: developed by Chinese people, with Chinese documents, there is no language barrier, easy to understand and learn;
  • Two-way data binding: retains the characteristics of Angular and is simpler in data operations;
  • Componentization: It retains the advantages of react, realizes the encapsulation and reuse of html, and has unique advantages in building single-page applications;
  • Separation of views, data, and structures: making data changes simpler, without the need to modify the logic code, and only need to operate the data to complete related operations;
  • Virtual DOM: DOM operations are very performance-intensive. The native DOM operation nodes are no longer used, which greatly liberates DOM operations. However, the specific operation of DOM is still done in another way;
  • Faster running speed: Compared with react, vue also operates virtual dom. In terms of performance, vue has great advantages.

What are the similarities and differences between v-show and v-if instructions?

What they have in common: Both can control the display and hiding of elements;
Differences: The implementation methods are different. The essence of v-show is to set the display in css to none and control the hiding, which will only be compiled once; v-if is a dynamic direction. Add or delete DOM elements in the DOM tree. If the initial value is false, it will not be compiled. Moreover, the constant destruction and creation of v-if consumes performance.
Summary: If you want to switch a node frequently, use v-show (the switching overhead is relatively small, but the initial overhead is large). If you don't need to switch a node frequently, use v-if (the initial rendering overhead is small, but the switching overhead is relatively large).

Vue parent component passes data to child component?

via props

Does child component pass events like parent component?

$emit method

How to make CSS only work in the current component?

Add scoped in front of the style in the component

What is the function of keep-alive?

keep-alive is a built-in component of Vue that allows included components to retain their state or avoid re-rendering.

How to get dom?

ref="domName" 用法:this.$refs.domName

Name several instructions in Vue and their usage?

  • v-model two-way data binding;
  • v-for loop;
  • v-if v-show show and hide;
  • v-on event;
  • v-once: Bind only once.

What is vue-loader? What are the uses for using it?

A loader for vue files that converts template/js/style into js modules.
Purpose: js can be written in es6, style can be scss or less, template can be added with jade, etc.

Why use key?

A key needs to be used to uniquely identify each node, and the Diff algorithm can correctly identify this node.
The main function is to update the virtual DOM efficiently.

Use of v-modal

v-model is used for two-way binding of form data. In fact, it is a syntactic sugar. It does two operations behind it:
v-bind binds a value attribute;
the v-on instruction binds an input event to the current element.

Please tell me the usage of each folder and file in the src directory in the vue.cli project?

  • The assets folder is for static resources;
  • components are components;
  • Router defines routing-related configuration;
  • app.vue is an application main component;
  • main.js is the entry file.

Briefly describe the usage scenarios of computed and watch respectively.

computed:
    When an attribute is affected by multiple attributes, you need to use computed.
    The most typical example: When checking out shopping cart items
watch:
    When one piece of data affects multiple pieces of data, you need to use watch.
    Example: Search data

Can v-on listen to multiple methods?

Yes, example:<input type="text" v-on="{ input:onInput,focus:onFocus,blur:onBlur, }">。

Use of $nextTick

When you modify the value of data and then immediately obtain the value of the dom element, you cannot obtain the updated value.
You need to use the $nextTick callback to let the modified data value render and update to the dom element before obtaining it successfully. .

Why does data in the vue component have to be a function?

Because of the characteristics of JavaScript, in component, data must exist in the form of a function and cannot be an object.
The data in the component is written as a function, and the data is defined in the form of function return value. In this way, every time the component is reused, a new data will be returned, which is equivalent to each component instance having its own private data space. They only Responsible for maintaining their own data without causing confusion. If simply written in object form, all component instances share the same data, so changing one of them will change all of them.

How is two-way data binding implemented in Vue?

Vue two-way data binding is achieved through data hijacking combined with the publish and subscribe model. That is to say, the data and the view are synchronized, the data changes, the view changes, the view changes, the data also changes; Core: About VUE two-
way Data binding, its core is the Object.defineProperty() method.

The differences, advantages and disadvantages between single-page applications and multi-page applications

A single page application (SPA), in layman's terms, refers to an application with only one main page. The browser must load all necessary html, js, and css at the beginning. All page content is contained in this so-called main page. But when writing, they will still be written separately (page fragments), and then dynamically loaded by the routing program during interaction. Single-page page jumps only refresh local resources. Mostly used on PC.
Multi-page (MPA) means that there are multiple pages in an application, and the entire
page is refreshed when the page jumps. The advantages of a single page:
good user experience, fast, and content changes do not require reloading the entire page. Based on this, SPA is very suitable for The server pressure is less; the front and back ends are separated; the page effects will be cooler (such as special animations when switching page content).
Disadvantages of single page:
not conducive to SEO; navigation is not available. If you must navigate, you need to realize forward and backward by yourself. (Because it is a single page and you cannot use the browser's forward and backward functions, you need to build your own stack management); it takes a lot of time to load for the first time; the page complexity increases a lot.

Priority of v-if and v-for

When v-if is used with v-for, v-for has higher priority than v-if, which means that v-if will be run repeatedly in each v-for loop separately. Therefore, it is not recommended to use v-if and v-for at the same time.
If v-if and v-for are used together, Vue will automatically prompt that v-if should be placed in the outer layer.

The difference between assets and static

Similar points : assets and static both store static resource files. The resource file images, font icons, style files, etc. required in the project can be placed under these two files. These are the similarities and differences
: the static resource files stored in assets are packaged when the project is packaged, that is, running npm run When building, the static resource files placed in assets will be packaged and uploaded. The so-called simplicity of packaging can be understood as compression volume and code formatting. The compressed static resource files will eventually be placed in the static file and uploaded to the server along with index.html. Static resource files placed in static will not go through processes such as packaging, compression and formatting. Instead, they will go directly to the packaged directory and be uploaded directly to the server. Because compression is avoided and uploaded directly, a certain degree of efficiency will be improved during packaging. However, since the resource files in static are not compressed, the file size is larger than the files packaged in assets. It will take up more space in the server.
Suggestion : Place the style files, js files, etc. required by the template in the project in assets and go through the packaging process. Reduce volume. The third-party resource files introduced in the project, such as iconfoont.css and other files, can be placed in static. Because these imported third-party files have been processed, we no longer need to process them and upload them directly.

Commonly used modifiers in vue

  • .stop: Equivalent to event.stopPropagation() in JavaScript to prevent events from bubbling;
  • .prevent: Equivalent to event.preventDefault() in JavaScript, preventing the execution of preset behaviors (if the event can be canceled, cancel the event without stopping the further propagation of the event);
  • .capture: In the opposite direction of event bubbling, event capture is from outside to inside;
  • .self: Only events within its own scope will be triggered, excluding child elements;
  • .once: Will only be triggered once.

Two core points of vue

Data-driven, component system
Data-driven: ViewModel, ensuring the consistency of data and views.
Component system: Application UI can be seen as entirely composed of component trees.

The difference between vue and jQuery

jQuery uses selectors ( $) to select DOM objects and perform operations such as assignment, value taking, event binding, etc. In fact, the only difference from native HTML is that it can more conveniently select and operate DOM objects, and the data and interface are in together. For example, if you need to get the content of the label label :$("lable").val(), it still depends on the value of the DOM element.
Vue completely separates data and View through Vue objects. To operate on data, you no longer need to reference the corresponding DOM object. It can be said that data and View are separated. They are bound to each other through the Vue object, the vm. This is the legendary MVVM.

Steps to introduce components

Introduce the component in the template;
use import to introduce the path in the first line of the script;
use component to write the component name.

The difference between delete and Vue.delete to delete an array

delete only changes the deleted element to empty/undefined and the key values ​​of other elements remain unchanged. Vue.delete directly deletes the array and changes the key value of the array.

How to solve the slow loading of SPA first screen

Install the required plug-ins for dynamic lazy loading; use CDN resources.

What is the difference between Vue-router jump and location.href

Use location.href='/url' to jump, which is simple and convenient, but refresh the page;
use history.pushState('/url'), no page refresh, static jump;
introduce router, and then use router.push(' /url') to jump, using the diff algorithm to achieve on-demand loading and reduce DOM consumption.
In fact, there is no difference between using router to jump and using history.pushState(), because vue-router uses history.pushState(), especially in history mode.

vue slot

To put it simply, if the parent component needs to put some DOM in the child component, then the slot distribution is responsible for whether the DOM is displayed, not displayed, where to display it, and how to display it.

The router-link in Vue works on the computer, but it doesn't respond on Android. How to solve it?

There is a problem with Vue routing on the Android machine. It is a babel problem. Install the babel polypill plug-in to solve it.

Solution to invalid events registered on router-link in Vue2

Use @click.native.
Reason: router-link will prevent click events, and .native means directly listening to a native event.

RouterLink does not work in IE and Firefox (route does not jump)

Method 1: Only use a tag, not button tag;
Method 2: Use button tag and Router.navigate method

What are the characteristics of axios

Create XMLHttpRequests from the browser;
node.js creates http requests;
supports Promise API;
intercepts requests and responses;
converts request data and response data;
cancels requests;
automatically changes to json.
The parameters of the sending field in axios are data and params. The difference between the two is that params is sent together with the request address. Data is sent as a request body. Params is generally suitable for get requests, and data is generally suitable for post put requests
. .

Please tell me the process of encapsulating vue components?

  • To create a component template, first set up the shelf, write the style, and consider the basic logic of the component.
  • Prepare the data input for the component. That is, analyze the logic and determine the data and types in props.
  • Prepare the component's data output. That is, according to the component logic, the methods to be exposed are prepared.
  • After encapsulation is completed, you can call it directly

The difference between params and query

Usage: Query should be introduced with path, params should be introduced with name, and the received parameters are similar, namely this.$route.query.nameand this.$route.params.name.
URL address display: query is more similar to get parameters in our ajax, and params is similar to post. To put it simply, the former displays parameters in the browser address bar, while the latter does not display. Note: query refresh will not be lost
. Refreshing the data params in the query
will lose the data in the params.

Vue initialization page flashing problem

When using vue to develop, before vue is initialized, since div is not managed by vue, the code we write will easily appear blurred before it is parsed. You will see words similar to {{message}}, although Under normal circumstances, this time is very short, but we still need to solve this problem.

/*首先:在css里加上*/
[v-cloak] {
    
    
	display: none;
}

If the problem is not completely solved, add style="display: none;" :style="{display: 'block'}" to the root element

Method to trigger view update when vue updates array

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

What is the vue life cycle? what's the effect?

Each Vue instance must go through a series of initialization processes when it is created - for example, it needs to set up data monitoring, compile templates, mount the instance to the DOM, and update the DOM when the data changes, etc.
At the same time, some functions called life cycle hooks will also be run during this process, which gives users the opportunity to add their own code at different stages. (ps: life cycle hooks are life cycle functions)
For example, if you want to operate DOM nodes through some plug-ins, if you want to pop up an advertising window after the page is rendered, we can do it in mounted at the earliest.

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

beforeCreate, created, beforeMount, mounted

Briefly describe which scenarios each cycle is suitable for

  • beforeCreate: After a new vue instance, there are only some default life cycle hooks and default events, and nothing else has been created yet. When the beforeCreate life cycle is executed, the data in data and methods have not yet been initialized. Data in data and methods in methods cannot be used at this stage.
  • create: data and methods have been initialized. If you want to call methods in methods or operate data in data, you can do it at this stage at the earliest.
  • beforeMount: When this hook is executed, the template has been compiled in the memory, but has not been mounted to the page. At this time, the page is still old.
  • mounted: When this hook is executed, it means that the Vue instance has been initialized. At this point, the component leaves the creation phase and enters the running phase. If we want to operate the DOM nodes on the page through a plug-in, we can do it at the earliest stage
  • beforeUpdate: When this hook is executed, the data displayed on the page is still old, the data in data is updated, and the page has not yet been synchronized with the latest data.
  • updated: The data displayed on the page and the data in the data have been synchronized and are both the latest.
  • beforeDestory: The Vue instance enters the destruction phase from the running phase. At this time, all data, methods, instructions, filters... are available. Not really destroyed yet
  • destroyed: At this time, all data and methods, instructions, filters... are in an unavailable state. The component has been destroyed.

The difference between created and mounted

created: Called before the template is rendered into HTML, that is, some attribute values ​​are usually initialized before rendering into a view.
mounted: Called after the template is rendered into HTML, usually after the initialization page is completed, and then performs some required operations on the DOM node of the HTML.

Vue gets the periodic function of the data

Generally created/beforeMount/mounted can be used.

Please explain in detail your understanding of the vue life cycle?

There are a total of 8 stages: before/after creation, before/after loading, before/after update, and before/after destruction.
Before/after creation: In beforeCreatedthe stage, the mounting elements $eland data objectsdata of the Vue instance are undefined and have not been initialized. In createdthe stage, the data object of the vue instance datais available, $elbut not yet.
Before/after loading: At beforeMountthis stage, the vue instance $el和datais initialized, but the virtual dom node before is still mounted, and data.message has not been replaced. In the mounted phase, the vue instance is mounted and data.message is successfully rendered.
Before/after update: When data changes, the beforeUpdateand updatedmethod will be triggered.
Before/after destruction: After executing destroythe method, changes to the data will no longer trigger the periodic function, indicating that the Vue instance has released event monitoring and binding to the DOM, but the DOM structure still exists.

What is the mvvm framework?

Vue is an mvvm framework that implements two-way data binding. When the view changes, the model layer is updated, and when the model layer changes, the view layer is updated. In vue, two-way binding technology is used, that is, changes in View can cause changes in Model in real time, and changes in Model can also be updated in real time to View.

What is vue-router? What components does it have?

Vue is used to write a routing plug-in. router-link, router-view

active-class is an attribute of which component?

The router-link component of the vue-router module. children array to define child routes

What kind of navigation hooks does vue-router have?

The first one is a global navigation hook: router.beforeEach(to,from,next). Its function is to judge and intercept before jumping.
The second type: hooks within the component
The third type: independent routing exclusive component
vue-router navigation hook

The difference between $route and $router

$routerIt is an instance of VueRouter. If you want to navigate to different URLs in the script tag, $router.pushhow to use it. Return the previous history to be used $router.to(-1)
$routeas the current router jump object. In it, you can get the name, path, query, parmas, etc. of the current route.

Two modes of vue-router

  • Hash mode: the # symbol in the URL in the address bar;
  • History mode: When the window.history object is printed, you can see the methods and record length provided inside. Utilizes the new pushState() and replaceState() methods in the HTML5 History Interface. (Requires specific browser support).

vue-router implements lazy loading of routes (dynamic loading of routes)

The first: vue asynchronous component technology ==== Asynchronous loading, vue-router configures routing, and uses vue's asynchronous component technology to achieve on-demand loading. However, in this case, a component generates a js file.
The second type: lazy loading of routes (using import).
The third type: require.ensure() provided by webpack, vue-router configures routing, and uses webpack's require.ensure technology to achieve on-demand loading. In this case, multiple routes specifying the same chunkName will be merged and packaged into a js file.
Implement lazy loading of routes

What is vuex? how to use? Which functional scenario uses it?

State management in the vue framework.
Introduce store in main.js, inject it, and create a new directory store.js,... Export
scenarios include: the status between components in a single-page application. Music playback, login status, add to shopping cart

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

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.
If it is reused elsewhere, this is most likely needed. If necessary, please put the request in the action to facilitate reuse.

What properties does vuex have?

There are five types, namely State, Getter, Mutation, Action, Module

  • state => basic data (data source storage location)
  • getters => data derived from basic data
  • mutations => Method to submit changed data, synchronized!
  • actions => is like a decorator, wrapping mutations so that they can be asynchronous.
  • modules => modularVuex

More interview question summaries

The above are common interview questions. There may be many more. I saw a lot of links on the Internet. I recommend
vue interview questions
. vue interview questions.

The above interview questions are summarized by myself. Please correct me if there are any mistakes.

Guess you like

Origin blog.csdn.net/weixin_45959525/article/details/120705813