Vue (continuously updated)
- 1. Can v-for and v-if be used in a mixed manner? Why?
- 2. Why add key in v-for?
- 3. The event has an event parameter by default. What is it? How to use it? Where are the events bound?
- 4. How do vue parent-child components communicate?
- 5. What are the order of periodic call for parent-child components?
- 6. What is the principle of vue two-way binding (responsive principle)?
- 7. What is $nextTick? Why prioritize micro-task resolution?
- 8. What is vuex? Why use it?
- 9. What is keep-alive? How to achieve it? life cycle? Should I execute activated or deactivated for the first time when loading, and why?
- 10. What is the difference between vue2 and vue3?
- 11. What are the implementation principles of history and hash routing? What is the difference?
- 12. Please tell me the commonly used design patterns? (More than 5 types) and give examples of usage scenarios in actual projects.
- 13. The nature of $emit and $on?
- 14. What is a virtual dom? principle? Pros and cons?
- 15. What is mixin? Pros and cons? principle? What replaced vue3?
- 16. Custom commands? principle?
- 17. The principle of event binding?
- 18. The principle of $set?
- 19. What are the advantages of Vue3 over Vue2?
- 20. Vue3 life cycle
- 21. Composition API and Options API
- 22. How to understand ref, toRef and toRefs
- 23. Why does ref need the value attribute?
- 24. What important functions have Vue3 been upgraded?
1. Can v-for and v-if be used in a mixed manner? Why?
Yes, but try not to use it at the same time
In Vue2,v-for
Calculate priority ratiov-if
High, first render the virtual node, and then proceedv-if
judge. Reduce rendering performance.
In Vue3,v-if
The priority is higher thanv-for
, but it is not recommended to use it at the same time. The official documentation recommends itv-for
It is mentioned outside for a layertemplate
Package, or raisev-if
。
Both mixed together are not officially recommended
2. Why add key in v-for?
If not usedkey
,Vue
Will use a way to minimize dynamic elements and try as much as possibleModify/reuse on-site
Algorithm for the same type of elements.keyYes forVue
middlevnode
The only mark of thiskey
,diff
The algorithm canMore accurate and faster
-
More accurate: Because
key
It's not reused on the spot,sameNode
Function === Comparison can avoid in-place reuse. So it will be more accurate. -
Faster:use
key
Uniqueness generationmap
Objects to obtain corresponding nodes faster than traversal methods
3. The event has an event parameter by default. What is it? How to use it? Where are the events bound?
When there are no parameters in the event, the default isevent
Parameters; if there are custom parameters, you need to use$event
Passed over.
-
event
The constructor ofMouseEvent
, that is, it is nativeevent
Object -
event
is mounted to the current element, i.e.
4. How do vue parent-child components communicate?
-
props、$emit:
Parent component uses dynamic data delivery, and child component usesprops
Receive, you can use array/object data structures, which can define types and default values.
Subcomponent usage$emit
Incident return
-
Custom events for component communication:
Custom events are just about using an extrajs
file, which declares oneVue
Just an example$on
,$emit
,$off
The parameters are: registered function name, real function
$on:Binding custom events
$emit: Call custom events
$off: When the component is destroyed, the custom event should be destroyed in time, otherwise memory leaks may occur. existbeforeDestroy
Called in$off
-
$refs:
Get the current component instance -
$parent&$children:
Get the parent and child components of the current component -
vuex:
A global state management system in Vue, used for data sharing in multiple components. -
provide&inject:
The upper component is provided and the lower component is injected into use. (Applicable to component library writing)
5. What are the order of periodic call for parent-child components?
-
Loading rendering process:
fatherbeforeCreate
-> Fathercreated
-> FatherbeforeMount
-> SubbeforeCreate
-> Subcreated
-> SubbeforeMount
-> Submounted
-> Fathermounted
-
Update process:
fatherbeforeUpdate
-> SubbeforeUpdate
-> Subupdated
-> Fatherupdated
-
Destruction process:
fatherbeforeDestroy
-> SubbeforeDestroy
-> Subdestroyed
-> Fatherdestroyed
-
The entire process:
beforeCreate
->created
->beforeMount
->mounted
->beforeUpdate
->updated
->beforeDestroy
->destroyed
6. What is the principle of vue two-way binding (responsive principle)?
Using data hijacking combined with observer mode
By hijacking each attribute (it will only hijack existing attributes)setter
,getter
,dep
andWatcher
Implement the process of dependency collection and distribution of updates:
-
vue
Willdata
Initialize to aObserver
And for each value in the object, rewritten theget
、set
,data
Each ofkey
, all have an independent onedep
(Depend on the collector). - exist
get
Middle, todep
(Dependency Collector) Added Listening - exist
mount
When an example isWatcher
, pointing the collector's target to the currentWatcher
- exist
data
When the value changes, triggerset
, triggereddep
(Depend on the collector) updates to trigger
7. What is $nextTick? Why prioritize micro-task resolution?
nextTick
The callback in the next timeDOM
The delayed callback executed after the update loop ends. Use this method immediately after modifying the data to obtain the updatedDOM
. The main idea is to use micro-task-first method to call asynchronous methods to executenextTick
Packaging method
8. What is vuex? Why use it?
vuex
It is specifically forvue
The provided global state management system is used for data sharing, data caching, etc. in multiple components. (Unable to persist, the internal core principle is to create a global instance new Vue)
It mainly includes the following modules:
- State: The data structure of the application state is defined, and the default initial state can be set here.
- Getter: Allow components to
Store
Get data frommapGetters
Helper functions simplystore
In-housegetter
Map to local computed properties. - Mutation: It's the only change
store
The method of state in it must be a synchronous function. - Action: Used to submit
mutation
, instead of changing the state directly, it can include any asynchronous operations. - Module: Allows single
Store
Split into multiplestore
And it is saved in a single state tree at the same time.
9. What is keep-alive? How to achieve it? life cycle? Should I execute activated or deactivated for the first time when loading, and why?
Functions and usage:
Cache component usage during developmentkeep-alive
Components,keep-alive
is a built-in component of vue,keep-alive
Wrap dynamic componentscomponent
Inactive component instances are cached instead of destroying them, thus keeping the state in memory during component switching, preventing repeated renderingsDOM
。
Use details:
Combined attributesinclude
andexclude
You can specify which components to cache or exclude cache specified components.vue3
Combinationvue-router
It changed a lot, beforekeep-alive
packrouter-view
, now you need to use it in reverserouter-view
packkeep-alive
。
keep-alive
It also used when cachedLRU(Least Recently Used)algorithm.
LRU (latest used) caching mechanism:
If keywordskey
Exist in the cache, return the value of the keyword, otherwise return-1
. If the keyword already exists, change its data value; if the keyword does not exist, insert the group"Keyword-value"
. When the cache capacity reaches the upper limit, it should delete the longest unused data value before writing new data, leaving room for the new data value
When components are cached and updated, the solutions can be as follows:
- beforeRouteEnter: There is
vue-router
The project will be executed every time it enters the routebeforeRouteEnter
。 - activated:
keep-alive
When the cached component is activated, it will be executedactivated
hook.
principle:
keep-alive
is a general component that defines an internalmap
, caches created component instances, and the rendering function it returns will look for embedded ones inside.component
Component corresponding componentsvnode
If the component is inmap
If it exists, it will be returned directly. becausecomponent
ofis
The attribute is responsive data, so as long as it changes,keep-alive
ofrender
The function will be executed again.
parameter:
keep-alive receives three parameters:
- include: You can pass strings, regular expressions, and arrays. Components that match successfully will be cached if they have successfully matched their names.
- exclude: You can pass strings, regular expressions, and arrays. Components that match successfully will not be cached.
- max: can pass numbers, limit the maximum number of cache components, if it exceeds max, it will be replaced according to the LRU algorithm
include and exclude, most cases of passing arrays are passed.
life cycle:
Life cycles include: activated activation, deactivated departure
- activated: When the page first enters, the order of the hook is created -> mounted -> activated
- deactivated: Deactivated will be triggered when the page exits
When moving forward or backward again, it only triggersactivated
。
usekeep-alive
The data will be retained inIn memoryIf you want to get the latest data every time you enter the page, you need toactivated
Get data in stages and bear the originalcreated
The task of getting data in the hook. Then, we usually use dynamic components and routing components.keep-alive
Components.
10. What is the difference between vue2 and vue3?
- Responsive system: vue2 is (); vue3 uses proxy
- vue3 is all refactored by ts, which is more friendly to ts support
- Custom renderer
- composition API
- vue3 can have multiple root nodes, vue2 can only have one
11. What are the implementation principles of history and hash routing? What is the difference?
hash mode
- 1.The value is actually
URL
middle#What follows is its characteristics:hash
Although it appearsURL
but not included inHTTP
In the request, there is no impact on the backend at all, so the changehash
The page will not be reloaded. - 2. Can be
hash
Changes to add listening events
window.addEventListener("hashchange", funcRef, false);
Every time you change hash(), a record will be added to the browser's access history.
Using the above features of hash, you can implement front-end routing"Update view but not re-request page"Functional
Features: Good compatibility but not beautiful
history mode
It utilizes the pushState() and replaceState() methods newly added in the HTML5 History Interface.
These two methods are applied to the browser's history site, currently availableback
、forward
、go
Based on the , they provide the function of modifying history. These two methods have a common feature: when they are called to modify the browser history stack, although the current one isURL
Changed, but the browser will not refresh the page, which is a front-end routing for a single page application"Update view but not re-request page"Provides the basis.
Features: Although beautiful, refresh will appear. 404 requires backend configuration
12. Please tell me the commonly used design patterns? (More than 5 types) and give examples of usage scenarios in actual projects.
-
1. Factory mode - Pass in parameters to create an instance
Virtual DOM returns the Vnode and component Vnode of the underlying tag according to the parameters
-
2. Singleton mode - There is only one instance in the entire program
vuex
andvue-router
Plugin registration methodinstall
If there is an instance in the system, return it directly -
3. Observer mode (responsive data principle)
-
4. Policy mode The policy mode refers to the object having a certain behavior, but in different scenarios, the behavior has different implementation solutions - such as the merge strategy of options
-
5. Policy mode: Optimize if else redundant code
-
6. Proxy mode: mini-vue proxy
13. The nature of $emit and $on?
- 1.
$on
、$emit
Based on the publish subscription model - 2.
$on
Used to collect all event dependencies, it will pass in parametersevent
andfn
Askey
andvalue
Save the form ofvm._events
In this event collection, it's like thisvm._events[event]=[fn]
; - 3. And
$emit
It is used to trigger events, and it will be transmitted according toevent
existvm_events
Find the corresponding event and execute itinvokeWithErrorHandling(cbs[i], vm, args, vm, info)
- 4. Finally, let's see
invokeWithErrorHandling
The method can be found that he passed(context, args)
and(context)
Execute the corresponding method in the form of
14. What is a virtual dom? principle? Pros and cons?
Use js to simulate a dom tree and place it in browser memory. When you want to change, the virtual dom uses the diff algorithm to compare the old and new virtual doms, put the changes into the change queue, and reflect it to the actual dom tree, reducing dom operations.
Virtual DOM converts the DOM tree into a JS object tree, and the diff algorithm compares, deletes, and adds operations layer by layer. However, if there are multiple identical elements, performance may be wasted, so react and vue-for introduce key values to distinguish them.
advantage:
- Guaranteed performance lower limit:The framework's virtual DOM needs to be adapted to any operations that may be generated by the upper API. Some of its DOM operations must be universal, so its performance is not optimal; but it is much better than the rough DOM operation, so the framework's virtual DOM can at least ensure that it can still provide good performance without manual optimization, that is, to ensure the lower limit of performance;
- No manual operation required:We no longer need to manually operate the DOM, we just need to write the code logic of View-Model. The framework will bind two-way to the virtual DOM and data, helping us update the views in an expected way, greatly improving our development efficiency;
- Cross-platform:Virtual DOM is essentially a JavaScript object, and DOM is strongly related to the platform. In contrast, virtual DOM can perform more convenient cross-platform operations, such as server rendering, weex development, etc.
shortcoming:
Unable to perform extreme optimization:Although the reasonable optimization of virtual DOM + is enough to meet the performance needs of most applications, virtual DOM cannot perform targeted and ultimate optimization in some applications with extremely high performance requirements.
When rendering a large number of DOM for the first time, the calculation of a layer of virtual DOM will be slower than innerHTML insertion.
15. What is mixin? Pros and cons? principle? What replaced vue3?
Sometimes there is the same code logic between components, which are divided intoPartial mixingandGlobal mixing, we hopeThe same code logic is extracted
- Mixin provides a very flexible way to distribute reusable features in Vue components
- A Mixin object can contain any component options—it is essentially an object
- When a component uses a Mixin object, all options for Mixin objects are mixed into the options of the component itself
shortcoming:
- The source of the variable is not clear, which is not conducive to reading
- Multiple mixins may cause naming conflicts
- There may be a many-to-many relationship between mixin and components, which is more complex
Vue3 uses the Composition API instead, the advantages:
- Code Extraction
- Code reuse
- Naming conflict resolution
16. Custom commands? principle?
Vue custom commands haveGlobal registrationandLocal registrationTwo ways. Let’s first look at the way to register global instructions, through(id, [definition])
WayRegister global commands. Then make a () call in the entry file.
Its value is when developers need to operate on ordinary DOM elements in certain scenarios. Improve code reuse.
Directives are essentially decorators, which are extensions of vue to HTML elements, adding custom functions to HTML elements. When vue compiles DOM, the instruction object will be found and the relevant methods of executing the instructions will be found.
Custom instructions have five life cycles (also called hook functions), namelybind
、inserted
、update
、componentUpdated
、unbind
- : Only called once, the instruction is called the first time it is bound to an element. Here you can perform one-time initialization settings.
- : Called when the bound element is inserted into the parent node (only the parent node exists, but it may not be inserted into the document).
- : Called when the template bound to the element is updated, regardless of whether the bound value changes. By comparing the binding values before and after the update, unnecessary template updates can be ignored.
- : Called when the template where the bound element is located has completed an update cycle.
- : Called only once, and is called when the instruction is unbined from the element.
principle
- 1. When generating the ast syntax tree, the directive will be added to the current element.
- 2. Generate instruction code through genDirectives
- 3. Extract the hook of the instruction into cbs before patch, and call the corresponding hook during patch process
- 4. When executing the corresponding hook function of the instruction, call the method defined by the corresponding instruction.
17. The principle of event binding?
$on and $emit are based on the publish subscription model, maintaining an event center. When on, the event is stored in the event center by name, and it is called a subscriber. Then emit publishes the corresponding event to execute the corresponding listener in the event center.
18. The principle of $set?
Because of responsive data, we add both the object and the array itself__ob__
Properties represent Observer instances. When adding non-existent properties to the object, the new properties will be responsively tracked and the object will be triggered.__ob__
ofdep
Collectedwatcher
To update, when modifying the array index, we call the array itselfsplice
Method to update the array
19. What are the advantages of Vue3 over Vue2?
- 1. Better performance
- 2. Smaller size
- 3. Better TS support
- 4. Better code organization
- 5. Better logical separation
- 6. More new features
20. Vue3 life cycle
- Options API
- Change to beforeUnmount
- Change to unmounted
- 3. Other life cycles that continue to use Vue2
- Composition API
setup
It's equivalent to integratingbeforeCreate
andcreated
The rest of the life cycles are written insetup
Functions in:- ()
- ()
- ()
- ()
- ()
- ()
21. Composition API and Options API
- 1. Better code organization
- 2. Better logical reuse
- 3. Better type deduction
How to choose?
- 1. It is not recommended to share, it will cause confusion
- 2. Small projects and business logic are simple, use the options API
- 3. Medium and large projects, complex logic, use composition API
22. How to understand ref, toRef and toRefs
ref:
- 1. Generate responsive data of value type
- 2. Can be used for templates and reactive
- 3. Pass
.value
Modify the value
toRef:
- 1. Prop for a reactive object (reactive encapsulation)
- 2. Create a ref with responsiveness
- 3. Maintain a reference relationship between the two
toRefs:
- 1. Convert reactive objects (reactive encapsulation) to normal objects
- 2. Each prop of the object is the corresponding ref (or the direct deconstruction of reactive responsive will lose the responsiveness)
- 3. Maintain a reference relationship between the two
23. Why does ref need the value attribute?
- is an object (responsiveness is not lost, value type cannot be proxyed with proxy), value stores value
- 2. Pass
.value
Attributesget
andset
Implement responsiveness - 3. When used in templates and reactive, it is not necessary
.value
, other situations require
24. What important functions have Vue3 been upgraded?
- Properties: declared in child components
emits
options
Binding events for parent component - 3. Life cycle: Use
setup
IntegrationbeforeCreate
andcreated``,beforeDestroy
Change tobeforeUnmount
,destroyed
Change tounmounted
, others are consistent with vue2 - 4. Multi-event processing: Write multiple processing functions in the click event and split with commas
- : Can store multiple root nodes
- 6. Remove
.sync
- 7. Writing asynchronous components: need to be introduced from Vue
defineAsyncComponent
, use this function to wrap import() to introduce asynchronous components - 8. Remove filter: Used in double brackets | Split conversion meaning
- : The main scenario is to increase the nesting level of components
- : Some use to load asynchronous components when they are not successful
loading
, the main implementation principle is named slots - API