


[Compilation and summary] 45+ Vue interview questions to help you consolidate your knowledge points!
This article will summarize and share with you some Vue interview questions (with answer analysis) to help you sort out basic knowledge and enhance Vue knowledge reserves. It is worth collecting, come and take a look!
1. Briefly describe the Vue life cycle
Answer ideas:
Vue
What is the life cycle?Vue
What are the stages of the life cycle?#Vue
Life cycle process?Combined with practice
Extension: Changes in
Vue3
Vue
Life cycle changes [Related Recommendation: vuejs video tutorial, web front-end development】
Answer example:
life The word cycle should be easy to understand, and we often encounter it in our lives. For example, when talking about a person's life cycle, we will say that a person will go through infancy, childhood, adolescence, youth, middle age, and old age in this life. several stages. The same is true for the life cycle of
Vue
. Each component inVue
will go through the process from creation to mounting to Update and then destroy these stages, and during these stages,Vue
will run a function called life cycle hook to facilitate us There are opportunities to add our own code at certain stages.The Vue life cycle can be divided into
8
phases: before and after creation, before and after mounting,Before and after update, before and after destruction, and the life cycle of some special scenes (keep-alive
when activated,When catching descendant component errors).Vue3
also adds three new scenes for debugging and server-side rendering.-
The hook function APIs corresponding to these stages are:
beforeCreate
create
beforeMount
mounted
beforeUpdate
updated
activated(called when keep-alive is activated)
deactivated(called when keep-alive is deactivated)
beforeDestory
destoryed
errorCaptured (called when capturing descendant component errors)
.Most of the changes in Vue3 just need to be prefixed with on, for example,
mounted
becomesonMounted
, exceptbeforeDestroy
anddestroyed
were renamed tobeforeUnmount
andunMounted
(This corresponds to the previousbeforeMount
andmounted
, obsessive-compulsive disorder expresses great appreciation ?) beforeCreate
Called before component creation, usually used to perform some initialization tasks in plug-in development;created
Called after the component is created, you can access various data, request interface data, etc.;mounted
Called when the component is mounted, you can access data,dom
Elements, sub-components, etc.;beforeUpdate
Called before update. Theview
layer has not been updated yet and can be used to obtain various states before update;updated
Called when the update is completed. At this time, the view layer has completed the update, and all states are already up to date;beforeUnmount
Called before the instance is destroyed. Can be used to cancel some timers or subscriptions;unMounted
Called when destroying an instance, it can clean up the links with other instances, unbind all its instructions and event listeners.In Vue3:
setup
is executed beforecreated
; and there is no beforeCreateand
created.
2. How to do permission management in Vue
- The general requirement for permission management is page permissions and button permissions manage
-
The specific implementation is divided into two solutions: front-end implementation and back-end implementation: The front-end solution will configure all routing information on the front-end , and require users to log in through the routing guard. After the user logs in, the routing table will be filtered out based on the role , and then dynamically add routes . For example, I will configure an
asyncRoutes
array, and the page that requires authentication will add aroles in the route's
metarouter.addRoutes(accessRoutes)
.The back-end solution will store all page routing information in the database . When the user logs in, all the routing information that he can access will be returned to the front-end based on his role query, and the front-end will pass
addRoute
Dynamically add routing information.The control of button permissions usually implements a command , such as
v-permission
, and passes the button required role to by valuev-permission
command, in themounted
hook of the command, you can determine whether the current user role and the button have an intersection. If so, keep the button. If not, keep the button. Remove button. The advantage of the pure front-end solution is that it is simple to implement and does not require additional permissions to manage the page, but maintenance problems are relatively big, there are new Page and role requirements require modifying the front-end code and repackaging and deploying; the server solution does not have this problem, through a dedicated role and permission management page, configure page and button permission information To the database, the application obtains the latest routing information every time it logs in.
My own words: Permission management is generally divided into page permissions and button permissions, and the specific implementation plan is divided into front-end implementation and back-end implementation. The front-end implementation will be on the front end. Maintain a dynamic routing array, filter the pages with permissions based on the user's role after logging in, and finally add the dynamic to router
through addRoute
; the backend implementation is different. The point is that these routes are returned by the backend to the frontend, and then dynamically added by the frontend.
Button permissions generally implement a v-permission
to control whether the button is displayed by determining whether the user has permission.
The advantage of the pure front-end solution is that it is simple to implement, but it has big maintenance problems. If there are new page and role requirements, the code needs to be changed and repackaged and deployed. This problem does not exist on the server side.
3. The use and principle of two-way binding in Vue
Answer ideas:
What is two-way binding?
What are the benefits of two-way binding?
Where to use two-way binding?
How to use two-way binding, usage details, changes in Vue3
Principle implementation description
Answer:
The two-way binding in Vue is a directive
v-model
, which can bind a responsive data to the view, and changes in the view can also change the value.v-model
is a syntactic sugar. Its principle (by default) is to hang variables to # through:value
##dom, and then change the value of the variable by monitoring the changes in
domthrough the
inputevent. The advantage of using
v-modelis convenience, which reduces a lot of tedious event processing and improves development efficiency.
- is usually used on forms
v-model
, and can also be used on custom components to represent a certain value input and output control.
- can be further limited by combining modifiers (lazy/number/trim), which is somewhat different when used on custom components. It is equivalent to giving a
modelValue# to the sub-component. ## attributes and
update:modelValue
events; in Vue3, you can also specify multiple different bindings in the form of parameters, such asv-model:foo
This is equivalent to The child component is given a property offoo
and an event ofupdate:foo
. - v-model
As a directive, its principle is that the Vue compiler will convert it into
value attribute binding and input listening events
, as mentioned above is by default. In fact, the compiler will allocate different events according to different form elements, such as checkbox andradio
typeinput
Will be converted tochecked
andchange
events.
There are the following types of communication between Vue components:
- props
$emit
、$on
、$off
、$once
(the last three (has been deprecated in Vue3)$children
(deprecated in Vue3)、$parent
$attrs
、$listeners
(Abolition in Vue3)-
ref
$root
##eventbus
-
vuex
、
pinia provide inject
The above method long press usage scenarios can be divided into:
- You can use
props
/
$emit/
$parent/
refbetween parent and child components /
$attrs - You can use
$parent
/
$rootbetween sibling components /
eventbus/
vuex - Can be used across layers and between components
eventbus
/
vuex pinia/
provide inject
5. What Vue performance optimization methods do you know?
- Route lazy loading: effectively split
App
size, load asynchronously only when accessed
const router = createRouter({ routes: [ { path : '/foo', component: () => import('./foo.vue)} ] })
- ## keep-alive
Cache page: avoid repeatedly creating component instances and save cached component status
<keep-alive> <router-view v-if="$route.meta.keepAlive == true"></router-view> </keep-alive> <router-view v-if="$route.meta.keepAlive != true"></router-view>
Copy after login
- Use
- v-show
Reuse
DOM
: avoid repeated creation of components ##v-for - traversal to avoid simultaneous use of
v-if
(actual This is the wrong way to write it in Vue3)
v-once - and
v-memo
Long list performance optimization: If it is a long list of big data, you can use Virtual scrolling only renders the content of a small area. Destruction of some open source libraries (: Use data that no longer changes
v-once; use
v-memo when skipping updates based on conditions vue-virtual-scroller - /
vue-virtual-scroll-grid
event: when the Vue component is destroyed , will automatically unbind all its instructions and event listeners, but only for events of the component itself.)
- Lazy loading of images, customized v-lazy
- instructions (reference project:
vue-lazyload
Third-party plug-ins are introduced on demand)
element-plus - Avoid being too large
Sub-component splitting strategy: Heavier state components are suitable for splitting - SSR
- Server-side rendering solves the problem of slow first screen rendering
Thoughts:
Why is the Vuex state lost after refreshing?
- Solution
- Third-party library and principle discussion
- Personal understanding
- Answer:
Because Vuex only saves the state in memory, it will be lost after refreshing. If you want to persist, you must save it. stand up.
- You can use localStorage
- to store the state of
Vuex
You can use plugins like, and
storeto take the value out as
state The initial value ofis stored in
localStoragewhen
mutationis submitted.
vuex-persist - and
vuex-persistedstate
There are two questions here. One is what if the user manually changes. You can control which ones need to be persisted through plugin options. The internal principle is to perform unified processing by subscribing to
mutationchanges.
localStorage - ? Then didn’t the status in my
Vuex
My solution to the first problem is to clear the data by listening to thealso change? Second, because
localStorage APIcan only store strings, we can only convert the data into strings through
JSON.stringify, and when the data we store is
When referencing data of Map,
Set,
Function,
JSON.stringifywill change after conversion
{}and lost.
storage
window.addEventListener("storage", function () { localStorage.clear(); window.location.href = '/login' console.error("不要修改localStorage的值~~~"); });
There is no solution to the second problem , you can only choose not to apply the reference types
Map and Set.
7. Why does Vue3 use Proxy instead of defineProperty?
Idea:
Attribute interception Several ways
- Problems with defineProperty
- Advantages of Proxy
- Other considerations
- Answer:
- There are three common ways to intercept properties in JS
- :
defineProperty
,
getter/settersand
Proxy Vue2
中使用defineProperty
的原因是, 2013 年只能使用这种方式,由于该API
存在一些局限性,比如对于数组的拦截有问题,为此Vue
需要专门为数组响应式做一套实现。另外不能拦截那些新增、删除属性;最后defineProperty
方案在初始化时需要深度递归遍历处理对象才能对它进行完全拦截,明显增加了初始化的时间。以上两点在
Proxy
出现后迎刃而解,不仅可以对数组实现拦截,还能对Map
、Set
实现拦截;另外Proxy
的拦截也是懒处理行为,如果用户没有访问嵌套对象,那么也不会实施拦截,这就让初始化的速度和内存占用改善了。Proxy
有兼容性问题,完全不支持IE
8. 怎么实现路由懒加载?
思路:
必要性
何时用
怎么用
使用细节
回答:
当打包构建时,Javascript 抱回变得非常大,影响页面加载。利用路由懒加载我们能把不同路由对应的组件分割成不同的代码块,然后当路由被访问的时候才加载对应最贱,这样更加高效,是一种优化手段。
一般来说,对于所有的路由都使用动态导入是个好主意
给
component
选项配置一个返回 Promise组件的函数就可以定义懒加载路由.例如:
{ path: '/login', component: () => import('../views/login/Login.vue') },
结合注释
{ path: '/login', component: () => import(/* webpackChunkName: "login" */'../views/login/Login.vue') },
vite中结合rollupOptions定义分块 5. 路由中不能使用异步组件
9. history模式 和 hash 模式有何区别?
Vue-Router 有三个模式,其中 history 和 hash 更为常用。两者差别主要在显示形式和部署上,
hash模式在地址栏现实的时候有一个
#
,这种方式使用和部署都较简单;history模式url看起来更优雅没关,但是应用在部署时需要做特殊配置,web服务器需要做回退处理,否则会出现刷新页面404的问题。在实现上
hash
模式是监听hashchange
事件触发路由跳转,history
模式是监听popstate
事件触发路由跳转。
10. 说说 nextTick 的使用和原理?
在
Vue
中nextTick
是等待下一次DOM
更新刷新的工具方法。Vue
有一个异步更新策略,意思是如果数据变化,Vue
不会立刻更新DOM
,而是开启一个队列,把组件更新函数保存在队列中,在同一时间循环中发生的所有数据变更会异步的批量更新。这一策略导致我们对数据的修改不会立刻体现在DOM
上,此时如果想要获取更新后的DOM
状态,就需要使用nextTick
nextTick
接受一个函数,我们可以在这个函数内部访问最新的DOM
状态 在开发时,有两个场景我们会用到nextTick
:created
中想要获取DOM
;- 响应式数据变化后获取
DOM
更新后的状态;
nextTick
的原理:在Vue
内部,nextTick
之所以能够让我们看到DOM
更新后的结果,是因为我们传入的callback
会被添加到队列刷新函数的后面,这样等队列内部的更新函数都执行完毕,所有DOM
操作也就结束了,callback
自然能够获取最新的DOM
值。
11. v-for 和 v-if 优先级
先回答答案:在 vue2
中, v-for
的优先级更高
但是在 vue3
中, v-if
的优先级更高
拓展:无论什么时候,我们都不应该把 v-for
和 v-if
放在一起,
怎么解决呢?一是可以定义一个计算属性,让 v-for
遍历计算属性。二是可以把 if
移到内部容器里(ul
ol
)或者把v-for
移植外部容器(template
)中
vue2 Documentationvue3 Documentation
12. How to monitor Vuex status changes?
- ##watch
- store.subscribe()
watch method, you can listen in the form of a string
$store.state.xx;
subscribe The method parameter is a callback function, the callback function accepts
mutation objects and
state object, you can determine the listening target through
mutation.type.
The wtach method is simpler and easier to use, while
subscribe is a little more cumbersome. It is generally used in the
vuex plug-in (you can mention the vuex persistence plug-in
vuex-persist,
vuex-persistedstate)
13. What do you think are the shortcomings of Vuex?
- Does not support persistence and the page refresh state will be lost
- Using modules is cumbersome
- Not supported
ts
(or very unfriendly)
14. What are the similarities and differences between ref and reactive?
- Both can return responsive objects,
ref
returns Is a responsive
Refobject,
reactivereturns a responsive proxy object.
ref
is usually used to process single-value responses,
reactiveis used to process data of object type.
ref
needs to be accessed through
.value, which will automatically remove
refin the view, and
.valueis not required,
refcan receive objects or arrays but is still implemented internally by
reactive;
reactiveIf
Refis received, the object will be automatically removed
ref; Using the expansion operator to expand the reactive object returned by
reactivewill make it lose responsiveness. It can be combined with
toRefs()to convert the value into a
Refobject Expand later.
reactive
internally uses the
Prxoyproxy to intercept various operations on the object, and
refinternally encapsulates a
RefImplClass, set
get value/set value, intercept user access to values.
16. How to extend a component in Vue?
- Logical extensions:
mixins
,
extends,
composition api:
- Content expansion: slots
mixins Very flexible, but conflicting and confusing.
extends is a less commonly used option. The difference with
mixins is that it can only extend a single object and has a higher priority than
mixins.
The source cannot be clearly determined and may cause naming conflicts with variables in the current component , composition api These problems can be solved very well. The independent responsive module can be used to easily write independent logic and provide responsive data, which enhances the readability and maintainability of the code.
Extension: Vue.mixin (global mixin) Vue.extend (a bit like the inheritance of a class/component to create a subclass)
17. vue What is -loader?
vue-loader
is a webpack loader for handling single file components (SFC)
- because With
vue-loader
, we can write code in the form of
.vuefile and split the code into
template webpack
When packaging,
vue-loader## will be called in the form of
loaderWhen
- #vue-loader
is executed, it will use a separate
loader
chain for each language block inSFC
Processing, and finally assembling these individual blocks into the final component module
Cannot be directly change.
There is a one-way data flow principle in component development. It is common sense not to modify the data of the parent component in the child component.
If you really need to change it, please send an event to the parent component through emit. Modify
in parent component19. How to define dynamic routing and how to obtain the passed dynamic parameters?
We can use a dynamic field in the path to achieve this, such as /users/:id
where :id
is the path parameter.
It can be obtained through this.$route.parmas
, and there can be multiple parameters. The $route
object also exposes other useful information such as query
hash
etc.
20. Talk about your understanding of Vue data responsiveness
Thoughts:
What is responsiveness?
Why does vue need to be responsive?
what is the benefit?
How is vue’s responsiveness implemented, and what are its advantages and disadvantages?
New responsive changes in vue3
Answer:
Data responsiveness is a mechanism that can detect data changes and respond
One of the core issues to be solved in
vue
is to connect the data layer And the view layer drives view updates through data changes. To do this, the data needs to be processed responsively.Through data responsiveness plus virtual
DOM
andpatch
algorithms, we only need to operate data and care about business, without any need for tediousness TheDOM
operation improves development efficiency and reduces development difficulty.vue2
The core of implementing data responsiveness is to intercept data through theObject.defineProperty()
method. Whenget
Do dependency collection when data is generatedset
Do update notification when data is generated. This mechanism is very good at solving the problem of data responsiveness, but there are also shortcomings in actual use. For example, recursive traversal during initialization will cause performance loss; cannot monitor new or deleted attributes. , invue
, you need to use a specificAPI
likeVue.set/delete
to add and delete object array attributes, and Data structures such asMa
andSet
are also not supported.In order to solve these problems,
Vue3
rewrote this Partially implemented, using theProxy
proxy inES6
to respond to the data. It has many benefits, initialization performance and memory are greatly improved, and no specialAPI
is required, but it does not support theIE
browser.
21. What is done from template to render
Asktemplate
to render
The process is actually about the working principle of vue compiler
.
Idea:
Introducing the concept of a compiler
Explain the necessity of a compiler
Explain the compiler workflow
Answer:
There is a unique compilation module in Vue
calledcompiler
. Its main function is to compiletemplate
intojs
executablerender
Function#The reason why this compilation process is needed is to facilitate the writing of view templates in our universities. In comparison, we still prefer to use
HTML
to write views, which is intuitive and efficient. Hand-writtenrender
functions are not only inefficient, but also lose the ability to be optimized by the compiler.Vue
The compiler will first parsetemplate
(Parse
), and after the end, you will get an abstract syntax TreeAST
, and then perform deep processing conversion (transform
) onAST
, and finally generate the resultingAST
intojs
Code, that is,render
function
22. How to cache and update components
The cache component can use the
keep-alive
component, and include and exclude can specify which components are included and not included.Vue3
The use ofvue-router
has changed a lot. Previously,keep-alive
includedrouter -view
, nowrouter-view
containskeep-alive
If you want to get data after caching, you can use
actived
hook orbeforeRouteEnter
(a guard ofvue-router
)keep-alive
is A general component, which defines amap
internally, caches the created component instance, and the rendering function it returns will internally search for thevnode corresponding to the embedded
componentcomponent.
, if the modified component exists in the map, return it directly. Since theis
attribute ofcomponent
is a reactive data, as long as it changes, therender
function ofkeep-alive
will be re-executed. .
23. Virtual DOM
What is virtual
DOM
? The essence of virtualDOM
is aJavascript
object.Why introduce virtual
DOM
? (benefit) It can effectively reduce the number of operationsDOM
and facilitate cross-platform implementation.How to generate virtual DOM?
compiler
The compiler will compile thetemplate
template into a rendering function. This rendering function will be called during themount
mounting process, and the returned object isVirtualDOM
. After the mounting is completed, the update process will enter. If some responsive data changes, it will cause the component to berender
, at which time a newvirtual DOM
will be generated anddiff
will be done with the last rendering result. Operation, the minimum amount of operationsdom
, so as to update the view efficiently.
24. What is an asynchronous component
Asynchronous components will not be loaded immediately but will be loaded when needed. Loaded components. In large applications, we need to split the code into smaller chunks and use asynchronous components.
Not only can you lazily load components when routing is switched, you can also use asynchronous components in components to split the code more finely.
The simplest way to use asynchronous components is to directly specify a
loader
function todefineAsyncComponet
and combine it with the ES module to dynamically import the functionimport
Can be implemented quickly.Vue3
You can also use asynchronous components in conjunction with theSuspense
component.Asynchronous components are easily confused with routing lazy loading, which is actually not the same thing. Asynchronous components cannot be used to define lazy loading routes. It is handled by the
Vue
framework, and it isvue-router
that handles the loading of routing components. But you can use asynchronous components in lazy-loaded routing components.
25. Talk about Vue long list optimization ideas
- Avoid large data volume: you can use paging to obtain it
- Avoid rendering large amounts of data: virtual scrolling solutions such as vue-virtual-scroller only render data within the viewport range
- Avoid updates: You can use the
v-once
method to render only once - Optimize updates: cache group numbers through v-memo, conditionally update, improve usage, and avoid unnecessary updates
- Load data on demand: You can use
lazy loading
method , loading data when the user needs it.
26. computed & watch
computed
is a computed property,watch
is the listener.computed
is usually used to handle complex logic in templates, whilewatch
is usually used to monitor changes in a responsive object. During some operations,watch
can perform asynchronous operations, butcomputed
cannot.Computed properties pass an object with two options:
set
andget
, which are called computed properties that are both readable and writable. , if a function is passed, the default is theget
option,watch
can pass an object, set deep, immediate and other optionsvue3
There have been some changes inwatch
, for example, it can no longer detect a string expression other than a dot operator, and the newin
reactivity APIwatch
andwatchEffect
can completely replace thewatch
option and are more powerful
27. The difference between SPA and SSR What is it?
SPA
(Single Page Application) is a single page application. It is also generally called Client-side rendering, orCSR
for short. SSR (Server Side Render) is server-side rendering. It is also generally called Multiple Page Application (Mulpile Page Application), referred to as MPA.SPA
will only request thehtml
file for the first time, and then only theJSON
data will be requested, so the user experience Better, saves traffic, and puts less pressure on the server. But the loading time of the first screen will become longer, and it isSEO
unfriendly. In order to solve the above shortcomings, there is theSSR
solution. Since theHTML
content is generated once on the server, the first screen loads quickly, and search engines can also easily crawl the page information. But at the same time, theSSR
solution will also have problems such as performance and limited development.In terms of selection, if there are first-screen loading optimization needs and SEO needs, you can consider SSR.
But this is not the only alternative. For example, for some static websites that do not change frequently, SSR wastes resources. We can consider the pre-rendering solution. In addition,
nuxt.js/next.js
provides us with the SSG static website generation solution, which is also a good static website solution. Combined with some CI methods, it can achieve a good optimization effect.
28. diff 算法
回答思路:
diff算法是干什么的?
必要性
何时执行
具体执行方式
拔高:说一下vue3中的优化
回答:
Vue
中的diff
算法称为patching
算法,虚拟DOM要想转化为真实DOM就需要通过patch
方法转换。最初
Vue1.x
视图中农每个依赖均有更新函数对应,可以做到精确更新,因此不需要虚拟DOM
和patching
算法支持,但是这样粒度过细导致Vue1.x
无法承载较大应用;Vue2.x
中为了降低Watcher
粒度,每个组件只有一个Watcher
与之对应,此时就需要引入patching
算法才能精确找到发生变化的地方并高效更新。vue
中diff
执行的时刻是组件内响应式数据变更触发实例执行其更新函数时,更新函数会再次执行render函数
获得最新的虚拟DOM
,然后执行patch函数
,对比新旧虚拟DOM,将其转化为对应的DOM
操作。patch
过程是一个递归过程,遵循深度优先、同层比较的策略;以vue3
的patch
为例:- 首先判断两个节点是否为相同同类节点,不同则删除重新创建
- 如果双方都是文本则更新文本内容
- 如果双方都是元素节点则递归更新子元素,同时更新元素属性
- 更新子节点时又分了几种情况:
- 新的子节点是文本,老的子节点是数组则清空,并设置文本;
- 新的子节点是文本,老的子节点是文本则直接更新文本;
- 新的子节点是数组,老的子节点是文本则清空文本,并创建新子节点数组中的子元素;
- 新的子节点是数组,老的子节点也是数组,那么比较两组子节点,更新细节blabla
vue3
中引入的更新策略:编译期优化patchFlags
、block
等
29. 如何从0到1架构一个Vue项目,说说有哪些步骤,插件,目录结构怎么组织
从 0 创建项目我大致会做以下事情:项目构建、引入必要插件、代码规范、提交规范、常用库和组件
目前vue3项目我会用vite或者create-vue创建项目
接下来引入必要插件:vue-router、vuex/pinia、element-plus、antd-vue、axios等等
其他常用的库有 像lodash、dayjs、nprogress等等..
下面是代码规范: editorconfig、prettier、eslint
最后是提交规范,可以使用husky、Commitizen
目录结构我喜欢按照下面的结构来
+ |- /src + |- /assets 存放资源 + |- /img + |- /css + |- /font + |- /data + |- base-ui 存放多个项目中都会用到的公共组件 + |- components 存放这个项目用到的公共组件 + |- hooks 存放自定义hook + |- views 视图 + |- store 状态管理 + |- router 路由 + |- service 网络请求 + |- utils 工具 + |- global 全局注册、全局常量..
30. 你如何实现一个Vue-Router
一个 SPA
应用的路由需要解决的问题时页面跳转内容改变同时不刷新,同时路由还需要已插件形式存在,所以:
-
首先我会定义一个
createRouter
函数,返回路由器实例,实例内部做几件事;- 保存用户传入的配置项
- 监听
hash
或者popstate
事件 - 回调里根据
path
匹配对应路由
-
将
router
定义成一个Vue
插件,即实现install
方法,内部做两件事:- 实现两个全局组件:
router-link
和router-view
,分别实现页面跳转和内容显示 - 定义两个全局变量:
$router
和$route
,组件内可以访问当前路由和路由器实例
- 实现两个全局组件:
31. 什么情况需要使用Vuex模块?
在项目规模变大的之后,单独一个store对象会过于庞大臃肿,此时通过模块方式可以拆分来便于维护
可以按之前规则单独编写资规模代码,然后在主文件中通过
modules
选项组织起来:createStore({modules: {...}})
When using it, please note that you need to add the registered module name when accessing the submodule status. But at the same time
getters
,mutations
andactions
are in the global space and can be used in the same way as before. If you want to achieve complete splitting, you need to add thenamespace
option to the submodules. At this time, you need to add the namespace prefix when accessing them again.The module method can split the code, but its shortcomings are also obvious. It is cumbersome to use, error-prone, and the type system support is very poor, which cannot help us. pinia has obviously improved a lot in this area and it's time to switch over.
32. Why the vue component can only have 1 root node
vue2
Medium It is true that a component can only have one root, but components invue3
can already have multiple root components.The reason why this is needed is because
vdom
is a single-root tree structure, and thepatch
method starts from the root node when traversing Traversal, which requires only one root node. The component will also be converted to avdom
, which should naturally meet this requirement.vue3
The reason why multiple root nodes can be written is because the concept ofFragment
is introduced, which is an abstract node. If it is found that the component has multiple roots, create aFragment
node and use multiple root nodes as itschildren
. In the futurepathch
, if it is found to be aFragment
node, it will directly traversechildren
to create or update.
33. What are the usage scenarios of v-once?
v-once
is a built-in instruction ofvue
. Its function is to render the specified component or element only once and skip the future. Update it.If we have some elements or components that no longer need to change after initial rendering, in this case it is suitable to use
v-once
, so that even if these data change,vue
will also skip updates, which is a code optimization method.We only need to add
v-once
to the component or element that is used.
Added:
vue3.2
After that,v-memo
was added, This directive can conditionally cache templates and control their updates. The principle ofv-once
: When the compiler finds that there isv-once
, it will store the first calculation result in the cache object, component When rendering again, it will be obtained from the cache to avoid recalculation.
34. What scenarios use nested routing?
- In daily development, some interfaces of the application are composed of multiple layers of nesting It is composed of components. In this case, each part of
url
usually corresponds to a nested component. Nested routing can be used invue-router
to express this relationship. - The manifestation is that when switching between two routes, they have common view content. At this time, a parent component is usually extracted and
view-router
is placed inside to form a physical nesting that corresponds to the logical nesting. When defining nested routes, use thechildren
attribute to organize the nested relationship. - In principle, the depth of nesting is determined inside the
router-view
component, and this The depth is used as the index of the matched component arraymatched
to obtain the corresponding rendering component and render it.
If you can’t explain it, just give an example. When I develop a page, if I need to display a top navigation bar and jump to different pages through the navigation bar, and the top navigation bar must be displayed on every page, I can use nested routing; I can also give an example , when I need to view the details page of a list, I often need nested routing (detail/:id
)
35. How to monitor Vuex status changes?
- ##watch
- store.subscribe()
watch method, you can listen in the form of a string
$store.state.xx;
subscribe The method parameter is a callback function, the callback function accepts
mutation objects and
state object, you can determine the listening target through
mutation.type.
The wtach method is simpler and easier to use, but
subscribe is a little more cumbersome, generally
36. What happened during the Vue instance mounting process?
- The process of mounting an instance is the process of app.mount(). On the whole, it does two things:
Initialization and Establishment Update mechanism
- Initialization meeting
Create component instance, Initialize component status,Create various responsive data
Resume update mechanism This step will immediately execute a component update function, which will execute the rendering function for the first time and execute
patch
to convert the previously obtainedvnode
todom
; At the same time, it will create a dependency between its internal responsive data and the component update function, so that the corresponding update function will be executed when the data changes in the future.
37. The role of key
The role of key
is mainly for more efficient Update virtualDOM
.key
is the key condition forvue
to determine whether two nodes are the same node during thepatch
process (another One is the element type), ifkey
is not set, its value isundefined
,vue
may always think that these are two identical nodes, and can only go Doing update operations, which results in a large number ofdom
update operations, is obviously not advisable.key
must be set during actual use, and the use of array indexes should be avoided as much as possible, which may lead to some hiddenbug
.
38. watch and watchEffect
##watchEffect
Run the function immediately and track it passively dependency, the function passed in depends on the collected data source and is also a callback function;
watchdetects one or more responsive data sources and calls a callback function when the data source changes, through ## The #immediate
option can also be set to execute immediately.- watchEffect
is a special
watch
. If you don't care about the values before and after the responsive data, you can usewatchEffect
. In other cases,watch
can be used.
parent created -> child created -> child mounted -> mounted parent
Reason:
Vue Creation is a recursive process, Create the parent component
first, If there are sub-components, the sub-components will be created, so create There is a parent component first and then a child component; when the child component is first created, Mounted hooks will be added to the queue, and they will be executed after patch
is completed. You can see the mounted# of the child component. ## Hooks are
selected into the queue , so wait until
patch finishes executing these hooks. 40. Talk about your understanding of Vuex
##vuex is a state management pattern library specially developed for vue applications,
When you encounter multiple components sharing state or when the components in the project are difficult to manage, you can use vuex, which manages the global state in a global singleton mode.
The basic core concepts include state, mutation, action, getters, module, etc.
Tell me some feelings about the use process. ts is not friendly and the module is cumbersome to use. The data will also disappear when the page is refreshed
- #41. What is a recursive component? What are the usage scenarios?
#If a component refers to itself through the component name, this is a recursive component.
-
Components such as
Tree and - Menu
, their nodes often contain child nodes, and the child node structure is often the same as the parent node. . The data of such components is often in a tree structure, which is a typical scenario for using recursive components.
42. Have you ever written a custom instruction?
Using custom instructions is divided into definition, registration, and use
There are two ways to define, object and function form, The former is similar to component definition and has various life cycles; the latter will only be executed when
mounted- and
- updated
app.directiveRegistration: You can use
Global registration can also be registered locally through the option Just add v- before the registration name when using it.
- v-copy Copy and paste
-
v-lazy Lazy loading of images -
v-debounce Anti-shake -
Button permission##v-permission
-
Long pressv-longpress
43. Vue3 new features
API level
Composition API
##setup
Syntax sugarTeleport
TeleportFragments
Can have multiple root nodesEmits
createRenderer
Custom Renderer-
cssSFC
State-driven Variables (v-bind in