During Vue interviews, frequently asked interview questions/Vue knowledge points are organized
Look at the interview questions, just to fill in any gaps and see what aspects you still don't understand. Remember not to think that memorizing interview questions means everything is fine. It's best to understand the underlying principles so that you can have a smooth conversation during the interview. Otherwise, a slightly skilled interviewer can tell at a glance whether they have real talent and knowledge or have just memorized this interview question.
(These are all basic vue interview questions, so there's no need to waste time looking down.)
1、 What is your understanding of MVVM?
MVVM is the abbreviation for Model View View Model.
A Model represents a 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 transforming the data model into a UI for presentation.
ViewModel listens to changes in model data, controls view behavior, and handles user interaction. Simply understood, it is an object that synchronizes View and Model, connecting Model and View.
In the MVVM architecture, there is no direct connection between View and Model, but rather interaction through ViewModel. The interaction between Model and ViewModel is bidirectional, so changes in View data are synchronized to the Model, and changes in Model data are immediately reflected on the View.
ViewModel connects the View and Model layers through bidirectional data binding, and the synchronization between View and Model is completely automatic without human intervention. Therefore, developers only need to focus on business logic, do not need to manually operate DOM, and do not need to pay attention to data state synchronization issues. Complex data state maintenance is completely managed by MVVM.
Bg2015020110.png
2、 Vue's lifecycle
Before creating, data observation and initialization events have not yet started
Created (after creation) completes data observation, property and method operations, initializes events, and the $el attribute has not yet been displayed
Before Mount is called before the start of the mount, and the relevant render function is called for the first time. The instance has completed the following configuration: compile the template and generate HTML from the data and template in the data. Please note that the HTML has not been attached to the page at this time.
Mounted (after loading) is a newly created VM in EL$ El, and mount it 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 HTML rendering in the template to the HTML page. Perform ajax interaction during this process.
BeforeUpdate is 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 additional re rendering processes.
Updated is called after the virtual DOM is re rendered and patched due to data changes. When called, the component DOM has been updated, so DOM dependent operations can be performed. However, in most cases, changing the state during this period should be avoided as it may result in an infinite loop of updates. This hook is not called during server-side rendering.
BeforeDestroy is called before the instance is destroyed. The instance is still fully available.
Destroyed is called after the instance is destroyed. After the call, all event listeners will be removed and all child instances will also be destroyed. This hook is not called during server-side rendering.
What is the Vue lifecycle?
Answer: The process from creation to destruction of Vue instances is the lifecycle. The lifecycle of Vue is a series of processes, including creating, initializing data, compiling templates, mounting Doms, rendering, updating, rendering, and destroying.
What is the role of the Vue lifecycle?
Answer: It has multiple event hooks in its lifecycle, making it easier for us to form good logic when controlling the entire Vue instance process.
How many stages are there in the Vue lifecycle?
Answer: It can be divided into a total of 8 stages: before/after creation, before/after loading, before/after updating, and before/after destruction.
Which hooks will trigger the first page load?
Answer: The following beforeCreate, created, beforeMount, and mounted will be triggered.
In which cycle has DOM rendering been completed?
Answer: The DOM rendering is already completed in mounted.
3、 The principle of Vue implementing bidirectional data binding: Object. defineProperty()
The main way to achieve bidirectional data binding in Vue is to use a combination of data hijacking and publisher subscriber mode, using Object. defineProperty() to hijack the setters and getters of various properties, and publish messages to subscribers when data changes, triggering corresponding listening callbacks. When passing a regular Javascript object to a Vue instance as its data option, Vue will traverse its properties and convert them to getters/setters using Object. defineProperty. Users cannot see getters/setters, but internally they allow Vue to track dependencies and notify changes when attributes are accessed and modified.
The bidirectional data binding of Vue uses MVVM as the entry point for data binding, integrating Observer, Compile, and Watcher. Through Observer, it listens for data changes in its own model, parses compilation template instructions through Compile (used in Vue to parse {{}}), and finally uses Watcher to build a communication bridge between Observer and Compile, achieving data changes ->view updates; View interaction change (input) ->bidirectional binding effect of data model change.
Implementing Simple Bidirectional Binding with JavaScript
<div id="app">
<input type="text" id="txt">
<p id="show"></p>
4、 Parameter transfer between Vue components
- Parent component and child component passing values
The parent component passes to the child component: the child component receives data through the props method;
Child component passing to parent component: $exit method passing parameters - Data transfer between non parent-child components, and value transfer between sibling components
EventBus is the creation of an event center, equivalent to a transit station, that can be used to transmit and receive events. The project is relatively small, so this is more suitable. (Although many people recommend using VUEX directly, it depends on the requirements. Technology is just a means, achieving the goal is the king's way.)
5、 Route Implementation of Vue: Hash Mode and History Mode
Hash mode: In the browser, the symbol '#', followed by the characters' # ', is called a hash, which is read using window. location. hash;
Feature: Although hash is in the URL, it is not included in HTTP requests; Used to guide browser actions, useless for server security, 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, a 404 error will not be returned.
History mode: History adopts the new features of HTML5; And two new methods are provided: pushState (), replaceState () to modify the browser history stack, and to listen for state changes in popState events.
In the history mode, the front-end URL must be consistent with the actual URL that initiates the request from the backend, such as http://www.xxx.com/items/id . If the backend lacks routing processing for/items/id, it will return a 404 error. In the official website of Vue Router, it is described as follows: "However, to play this mode well, backend configuration support is also required... So, you need to add a candidate resource on the server that covers all situations: if the URL cannot match any static resources, you should return to the same index. html page, which is the page that your app depends on
6、 What is the difference between Vue, Angular, and React?
(The versions are constantly updated, and the following differences may not be very accurate. I only use Vue in my work and am not very familiar with Angular and React.) - Differences from AngularJS
Similarities:
Both support instructions: built-in instructions and custom instructions; Both support filters: built-in filters and custom filters; Both support bidirectional data binding; None of them support low-end browsers.
Differences:
AngularJS has a high learning cost, such as adding the Dependency Injection feature, while Vue.js itself provides a relatively simple and intuitive API; In terms of performance, AngularJS relies on dirty checking of data, so the more Watchers, the slower; Vue.js uses dependency tracking based observation and asynchronous queue updates, and all data is independently triggered. - Differences from React
Similarities:
React adopts a special JSX syntax, and Vue. js also advocates writing. Vue special file formats in component development, with some conventions for file content, both of which need to be compiled and used; The central idea is the same: everything is a component, and component instances can be nested; Provide reasonable hook functions that allow developers to customize requirements; They do not have built-in column count AJAX, Route, and other functions in the core package, but are loaded as plugins; Mixins feature is supported in component development.
Differences:
The Virtual DOM used by React will perform dirty checks on the rendered results; Vue.js provides instructions, filters, and more in the template, making it very convenient and fast to operate the Virtual DOM.
7、 Hook function for Vue routing
The homepage can control navigation jumps, beforeEach, afterEach, etc., and is generally used for modifying page titles. Some redirect functions that require login to adjust the page.
Before Each mainly has three parameters to, from, and next:
To: The target routing object that the route is about to enter,
From: route The current navigation is about to leave the route
Next: Function must call the method resolve hook. The execution effect depends on the calling parameters of the next method. Can control webpage redirection.
8、 What is vuex? How to use it? Which functional scenario uses it?
The states that are only used for reading are concentrated in the store; The way to change the state is to submit mutations, which is a synchronized thing; Asynchronous logic should be encapsulated in actions.
Introduce the store in main.js and inject it. Created a new directory store Export.
Scenarios include: in a single page application, the status between components, music playback, login status, and adding to the shopping cart
Picture description
State
Vuex uses a single state tree, meaning that each application will only contain one store instance, but a single state tree and modularity do not conflict. The stored data status cannot be directly modified.
Mutations
The methods defined by mutations dynamically modify the state or data in Vuex's store.
Getters
Computational attributes similar to Vue are mainly used to filter some data.
Action
Actions can be understood as transforming the data processing methods in mutations into asynchronous data processing methods, which in simple terms are asynchronous operations on data. The view layer distributes actions through store.dispath.
const store = new Vuex.Store({ //store
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
increment (context) {
context.commit('increment')
}
}
})
modules
When the project is particularly complex, each module can have its own state, mutation, action, and getters, making the structure very clear and easy to manage.
const moduleA = {
state: { ... },
mutations: { ... },
actions: { ... },
getters: { ... }
}
const moduleB = {
state: { ... },
mutations: { ... },
actions: { ... }
}
const store = new Vuex.Store({
modules: {
a: moduleA,
b: moduleB
})
9、 How can Vue cli add custom instructions?
- Create local instructions
var app = new Vue({
el: '#app',
data: {
},
// Create instructions (can have multiple)
directives: {
// Instruction Name
dir1: {
inserted(el) {
// The first parameter in the instruction is the DOM of the currently used instruction
console.log(el);
console.log(arguments);
// Operate on DOM
el.style.width = '200px';
el.style.height = '200px';
el.style.background = '#000';
}
}
}
})
2.Global Directives
Vue.directive('dir2', {
inserted(el) {
console.log(el);
}
})
3.Use of instructions
十、How can Vue customize a filter?
html code:
JS code:
var vm=new Vue({
el:"#app",
data:{
msg:''
},
filters: {
capitalize: function (value) {
if (!value) return ''
value = value.toString()
return value.charAt(0).toUpperCase() + value.slice(1)
}
}
})
Global Definition Filter
Vue.filter('capitalize', function (value) {
if (!value) return ''
value = value.toString()
return value.charAt(0).toUpperCase() + value.slice(1)
})
The filter receives the value of the expression (msg) as the first parameter. The capitalization filter will receive the value of msg as the first parameter.
11、 What is your understanding of keep alive?
Keep alive is a built-in component of Vue that can preserve the state of the included components or avoid re rendering.
After version 2.1.0 of Vue, keep alive added two new attributes: include (cache of included components) and exclude (exclude components are not cached and have a higher priority than include).
Usage method
<keep alive include='include_ Components' exclude='exclude_ Components
<-- Whether this component is cached depends on the include and exclude attributes -->
Parameter Interpretation
Include - String or regular expression, only components with matching names will be cached
Exclude - Strings or regular expressions, any components with matching names will not be cached
The properties of include and exclude allow components to cache conditionally. Both can use "," to separate strings, regular expressions, and arrays. When using regexes or arrays, remember to use v-bind.
Usage examples
<-- Comma separated string, only components a and b are cached. -->
Keep alive include="a, b">
<-- Regular expression (requires the use of v-bind, all matching rules will be cached) -->
Keep alive: include="/a | b/">
<-- Array (requires the use of v-bind, everything contained will be cached) -->
Keep alive: include="['a ','b']">
12、 An interview question that can be answered in just one sentence
- CSS only works on the current component
Answer: Write scoped in the style tag, for example: - Differences between v-if and v-show
Answer: V-if is rendered according to the conditions, and V-show is the block or none of display; - Differences between $route and $router
Answer: $route is the "routing information object", including path, params, hash, query, fullPath, matched, name, and other routing information parameters. And $router is the "routing instance" object, which includes the jump method, hook function, and so on of the route.
What are the two cores of vue.js?
Answer: Data driven, component system - Several Common Instructions for Vue
Answer: V-for, V-if, V-bind, V-on, V-show, V-else - What are the commonly used modifiers for Vue?
Answer:. prevent: Submitting an event will no longer overload the page Stop: Prevent click events from bubbling Self: Triggered when an event occurs on the element itself rather than a child element Capture: Event listening, which will be called when an event occurs
Can V-on bind multiple methods?
Answer: Yes
What is the role of key values in Vue?
Answer: When Vue.js uses v-for to update the rendered element list, it defaults to using the "in place reuse" strategy. If the order of the data items is changed, Vue will not move DOM elements to match the order of the data items, but will simply reuse each element here and ensure that it displays each element that has been rendered under a specific index. The main function of key is to efficiently update the virtual DOM. - What are the computational properties of Vue?
Answer: Placing too much logic in a template can make it too heavy and difficult to maintain. In situations where complex data processing is required and may be used multiple times, it is recommended to use the method of calculating attributes as much as possible. Benefits: ① Clear data processing structure; ② Depends on data, updates data, and automatically updates processing results; ③ This points to the VM instance within the calculation attribute; ④ When calling the template, simply write the calculation property name; ⑤ The commonly used method is the getter method, which can obtain data or use the set method to change the data; ⑥ Compared to methods, regardless of whether the dependent data remains unchanged, methods will be recalculated. However, when the dependent data remains unchanged, computed is obtained from the cache and will not be recalculated. - Single page applications such as Vue and their advantages and disadvantages
Answer: Advantages: Vue's goal is to achieve responsive data binding and composite view components through the simplest possible API, with a responsive data binding system at its core. MVVM, data-driven, componentized, lightweight, concise, efficient, fast, and modular friendly.
Disadvantage: It does not support lower version browsers, and only supports IE9 at the minimum; Not conducive to SEO optimization (if you want to support SEO, it is recommended to use the server to render components); The first time loading the homepage takes a relatively long time; You cannot use the browser's navigation buttons and need to implement forward and backward actions yourself. - How to define dynamic routing for vue router? How to obtain the value passed in
Answer: In the index.js file in the router directory, add/: id to the path attribute and use the params. id of the router object to obtain it.
During Vue interviews, frequently asked interview questions/Vue knowledge points are organized - front-end real factory interview questions
Learning ES6 Notes - ES6 Grammar Commonly Used in Work