Home > Article > Web Front-end > [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!
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 in Vue
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
becomes onMounted
, except beforeDestroy
and destroyed
were renamed to beforeUnmount
and unMounted
(This corresponds to the previous beforeMount
and mounted
, 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. The view
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 before created
; and there is no beforeCreate and
created.
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 a roles in the route's
meta
field, after obtaining the user role, take the intersection of the two. If the result is not empty, it means it can be accessed. After filtering, the remaining routes are the pages that users can access. Finally, you can dynamically add routes through router.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 value v-permission
command, in the mounted
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.
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
dom through the
input event. The advantage of using
v-model is convenience, which reduces a lot of tedious event processing and improves development efficiency.
v-model, and can also be used on custom components to represent a certain value input and output control.
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 as v-model:foo
This is equivalent to The child component is given a property of foo
and an event of update:foo
.
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 and radio
type input
Will be converted to checked
and change
events.
$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
(It’s not easy to use in Vue3, you need to encapsulate it yourself)
vuex、
pinia
provide inject
The above method long press usage scenarios can be divided into:
props /
$emit/
$parent/
ref between parent and child components /
$attrs
$parent /
$root between sibling components /
eventbus /
vuex
eventbus /
vuex pinia /
provide inject
App size, load asynchronously only when accessed
const router = createRouter({ routes: [ { path : '/foo', component: () => import('./foo.vue)} ] })
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>
Reuse DOM
: avoid repeated creation of components
v-if (actual This is the wrong way to write it in Vue3)
v-memo: Use data that no longer changes
v-once; use
v-memo when skipping updates based on conditions
vue-virtual-scroll-grid)
vue-lazyload)
Why is the Vuex state lost after refreshing?
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.
Vuex, and
store to take the value out as
state The initial value of is stored in
localStorage when
mutation is submitted.
vuex-persistedstate. You can control which ones need to be persisted through plugin options. The internal principle is to perform unified processing by subscribing to
mutation changes.
Vuex also change? Second, because
localStorage API can 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.stringify will change after conversion
{} and lost.
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?
Attribute interception Several ways
defineProperty ,
getter/setters and
Proxy
Vue2
中使用 defineProperty
的原因是, 2013 年只能使用这种方式,由于该 API
存在一些局限性,比如对于数组的拦截有问题,为此 Vue
需要专门为数组响应式做一套实现。另外不能拦截那些新增、删除属性;最后 defineProperty
方案在初始化时需要深度递归遍历处理对象才能对它进行完全拦截,明显增加了初始化的时间。
以上两点在 Proxy
出现后迎刃而解,不仅可以对数组实现拦截,还能对 Map
、Set
实现拦截;另外 Proxy
的拦截也是懒处理行为,如果用户没有访问嵌套对象,那么也不会实施拦截,这就让初始化的速度和内存占用改善了。
Proxy
有兼容性问题,完全不支持IE
思路:
必要性
何时用
怎么用
使用细节
回答:
当打包构建时,Javascript 抱回变得非常大,影响页面加载。利用路由懒加载我们能把不同路由对应的组件分割成不同的代码块,然后当路由被访问的时候才加载对应最贱,这样更加高效,是一种优化手段。
一般来说,对于所有的路由都使用动态导入是个好主意
给 component
选项配置一个返回 Promise组件的函数就可以定义懒加载路由.例如:
{ path: '/login', component: () => import('../views/login/Login.vue') },
结合注释
{ path: '/login', component: () => import(/* webpackChunkName: "login" */'../views/login/Login.vue') },
vite中结合rollupOptions定义分块 5. 路由中不能使用异步组件
Vue-Router 有三个模式,其中 history 和 hash 更为常用。两者差别主要在显示形式和部署上,
hash模式在地址栏现实的时候有一个 #
,这种方式使用和部署都较简单;history模式url看起来更优雅没关,但是应用在部署时需要做特殊配置,web服务器需要做回退处理,否则会出现刷新页面404的问题。
在实现上 hash
模式是监听hashchange
事件触发路由跳转,history
模式是监听popstate
事件触发路由跳转。
在 Vue
中 nextTick
是等待下一次 DOM
更新刷新的工具方法。
Vue
有一个异步更新策略,意思是如果数据变化,Vue
不会立刻更新 DOM
,而是开启一个队列,把组件更新函数保存在队列中,在同一时间循环中发生的所有数据变更会异步的批量更新。这一策略导致我们对数据的修改不会立刻体现在 DOM
上,此时如果想要获取更新后的 DOM
状态,就需要使用 nextTick
nextTick
接受一个函数,我们可以在这个函数内部访问最新的 DOM
状态
在开发时,有两个场景我们会用到 nextTick
:
created
中想要获取 DOM
;DOM
更新后的状态;nextTick
的原理:在 Vue
内部,nextTick
之所以能够让我们看到 DOM
更新后的结果,是因为我们传入的 callback
会被添加到队列刷新函数的后面,这样等队列内部的更新函数都执行完毕,所有 DOM
操作也就结束了,callback
自然能够获取最新的 DOM
值。
先回答答案:在 vue2
中, v-for
的优先级更高
但是在 vue3
中, v-if
的优先级更高
拓展:无论什么时候,我们都不应该把 v-for
和 v-if
放在一起,
怎么解决呢?一是可以定义一个计算属性,让 v-for
遍历计算属性。二是可以把 if
移到内部容器里(ul
ol
)或者把v-for
移植外部容器(template
)中
vue2 Documentationvue3 Documentation
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)
ts (or very unfriendly)
ref returns Is a responsive
Ref object,
reactive returns a responsive proxy object.
ref is usually used to process single-value responses,
reactive is used to process data of object type.
ref needs to be accessed through
.value, which will automatically remove
ref in the view, and
.value is not required,
ref can receive objects or arrays but is still implemented internally by
reactive;
reactive If
Ref is received, the object will be automatically removed
ref ; Using the expansion operator to expand the reactive object returned by
reactive will make it lose responsiveness. It can be combined with
toRefs() to convert the value into a
Ref object Expand later.
reactive internally uses the
Prxoy proxy to intercept various operations on the object, and
ref internally encapsulates a
RefImpl Class, set
get value/set value, intercept user access to values.
mixins,
extends,
composition api:
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)
vue-loader is a webpack loader for handling single file components (SFC)
vue-loader, we can write code in the form of
.vue file and split the code into
template
script
style
webpack When packaging,
vue-loader## will be called in the form of
loader When
is executed, it will use a separate loader
chain for each language block in SFC
Processing, and finally assembling these individual blocks into the final component module
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 componentWe 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.
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
and patch
algorithms, we only need to operate data and care about business, without any need for tediousness The DOM
operation improves development efficiency and reduces development difficulty.
vue2
The core of implementing data responsiveness is to intercept data through the Object.defineProperty()
method. When get
Do dependency collection when data is generated set
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. , in vue
, you need to use a specific API
like Vue.set/delete
to add and delete object array attributes, and Data structures such as Ma
and Set
are also not supported.
In order to solve these problems, Vue3
rewrote this Partially implemented, using the Proxy
proxy in ES6
to respond to the data. It has many benefits, initialization performance and memory are greatly improved, and no special API
is required, but it does not support the IE
browser.
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
called compiler
. Its main function is to compile template
into js
executable render
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-written render
functions are not only inefficient, but also lose the ability to be optimized by the compiler.
Vue
The compiler will first parse template
( Parse
), and after the end, you will get an abstract syntax Tree AST
, and then perform deep processing conversion (transform
) on AST
, and finally generate the resulting AST
into js
Code, that is, render
function
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 of vue-router
has changed a lot. Previously, keep-alive
included router -view
, now router-view
contains keep-alive
If you want to get data after caching, you can use actived
hook or beforeRouteEnter
(a guard of vue-router
)
keep-alive
is A general component, which defines a map
internally, caches the created component instance, and the rendering function it returns will internally search for the vnode corresponding to the embedded
component component.
, if the modified component exists in the map, return it directly. Since the is
attribute of component
is a reactive data, as long as it changes, the render
function of keep-alive
will be re-executed. .
What is virtual DOM
?
The essence of virtual DOM
is a Javascript
object.
Why introduce virtual DOM
? (benefit)
It can effectively reduce the number of operations DOM
and facilitate cross-platform implementation.
How to generate virtual DOM? compiler
The compiler will compile the template
template into a rendering function. This rendering function will be called during the mount
mounting process, and the returned object is VirtualDOM
. After the mounting is completed, the update process will enter. If some responsive data changes, it will cause the component to be render
, at which time a new virtual DOM
will be generated and diff
will be done with the last rendering result. Operation, the minimum amount of operations dom
, so as to update the view efficiently.
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 to defineAsyncComponet
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 the Suspense
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 is vue-router
that handles the loading of routing components. But you can use asynchronous components in lazy-loaded routing components.
v-once
method to render only once lazy loading
method , loading data when the user needs it. computed
is a computed property, watch
is the listener.
computed
is usually used to handle complex logic in templates, while watch
is usually used to monitor changes in a responsive object. During some operations,
watch
can perform asynchronous operations, but computed
cannot.
Computed properties pass an object with two options: set
and get
, which are called computed properties that are both readable and writable. , if a function is passed, the default is the get
option, watch
can pass an object, set deep, immediate and other options
vue3
There have been some changes in watch
, for example, it can no longer detect a string expression other than a dot operator, and the new in
reactivity API watch
and watchEffect
can completely replace the watch
option and are more powerful
SPA
(Single Page Application) is a single page application. It is also generally called Client-side rendering, or CSR
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 the html
file for the first time, and then only the JSON
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 is SEO
unfriendly. In order to solve the above shortcomings, there is the SSR
solution. Since the HTML
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, the SSR
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.
回答思路:
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
为例:
vue3
中引入的更新策略:编译期优化 patchFlags
、block
等
从 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 全局注册、全局常量..
一个 SPA
应用的路由需要解决的问题时页面跳转内容改变同时不刷新,同时路由还需要已插件形式存在,所以:
首先我会定义一个 createRouter
函数,返回路由器实例,实例内部做几件事;
hash
或者 popstate
事件path
匹配对应路由将 router
定义成一个 Vue
插件,即实现 install
方法,内部做两件事:
router-link
和 router-view
,分别实现页面跳转和内容显示$router
和 $route
,组件内可以访问当前路由和路由器实例在项目规模变大的之后,单独一个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
and actions
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 the namespace
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.
vue2
Medium It is true that a component can only have one root, but components in vue3
can already have multiple root components.
The reason why this is needed is because vdom
is a single-root tree structure, and the patch
method starts from the root node when traversing Traversal, which requires only one root node. The component will also be converted to a vdom
, which should naturally meet this requirement.
vue3
The reason why multiple root nodes can be written is because the concept of Fragment
is introduced, which is an abstract node. If it is found that the component has multiple roots, create a Fragment
node and use multiple root nodes as its children
. In the future pathch
, if it is found to be a Fragment
node, it will directly traverse children
to create or update.
v-once
is a built-in instruction of vue
. 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 of
v-once
: When the compiler finds that there is v-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.
url
usually corresponds to a nested component. Nested routing can be used in vue-router
to express this relationship. view-router
is placed inside to form a physical nesting that corresponds to the logical nesting. When defining nested routes, use the children
attribute to organize the nested relationship. router-view
component, and this The depth is used as the index of the matched component array matched
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
)
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
Initialization and Establishment Update mechanism
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 obtained vnode
to dom
; 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.
The role of key
is mainly for more efficient Update virtual DOM
.
key
is the key condition for vue
to determine whether two nodes are the same node during the patch
process (another One is the element type), if key
is not set, its value is undefined
, vue
may always think that these are two identical nodes, and can only go Doing update operations, which results in a large number of dom
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 hidden bug
.
##watchEffectRun the function immediately and track it passively dependency, the function passed in depends on the collected data source and is also a callback function;
watch detects 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.
is a special watch
. If you don't care about the values before and after the responsive data, you can use watchEffect
. In other cases, watch
can be used.
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
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
Components such as
Tree, 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.
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
mountedRegistration: You can use
Just add v- before the registration name when using it.
##v-permission
v-longpress
43. Vue3 new features
Composition API
##setup
Syntax sugar
Teleport
Teleport
Fragments
Can have multiple root nodes
Emits
createRenderer
Custom Renderer
SFC
State-driven
)##In addition, Vue3 also has many two Points and improvements
DOM
RewritepatchFlags
, block
WaitProxy
The biggest design goal is to replace Vue2
. In order to achieve this, Vue3
is in the following aspects Great improvements have been made, such as: ease of use, framework performance, scalability, maintainability, development experience, etc.
Ease of use: mainly API
Simplified v-model
becomes a combination of v-model
and sync
modifiers. Similar to h(type,props,children)
, props
in the function does not need to consider distinguishing attributes, characteristics, events, etc., the framework makes the judgment for us, increasing the ease of use.
In terms of development experience: New components such as Teleport
Fragment
Suspense
will simplify code writing for specific scenarios. setup
Syntactic sugar has greatly improved our development experience.
Improvements in scalability: such as independent reactivity
modules, custom render API
, etc.
In terms of maintainability, it is mainly Composition API
, which makes it easier to write highly reusable business logic. There are also improvements to TS support.
Performance: Compiler optimization, responsive system based on Proxy
.
. . .
Code aspect: Brand new responsive API, implemented based on Proxy
, initialization events and memory usage have been greatly improved;
Compilation: More compilation optimization processing has been done, such as static promotion, dynamic content tagging, event caching, blocks, etc., which can effectively skip a large number of diff processes
Packaging: better support tree-shaking
, so the size is smaller and faster to load. (Because all APIs of vue3 are introduced through ES6 modularization, this allows webpack or Packaging tools such as rollup eliminate unused APIs during packaging to minimize the bundle size)
$attrs
and$listeners
What does it do? $attrs
Get attributes that are not defined in props
, v-bind="$attrs"
can be used for attributes Transparent transmission $listeners
is used to obtain events. vue3
has been removed and merged into attrs
, making it more convenient to use
Composition API
is a set of APIs, including Reactivity API
, life hooks, and dependency injection, allowing users to write components by importing functions, andOptions API
Write components by declaring the object form of component options.
Composition API
is more concise and logic reuse is more efficient. Solved various shortcomings of mixins
in the past Options API
(conflicts and confusion); in addition, Composition API
is more free and does not have Options API
Such a fixed writing method can more effectively organize the logical code together without making it confusing. Finally, Composition API
has better type inference, which is better for ts
Support is friendly.
Coding style:
Components Use a multi-word style when naming to avoid conflict with html elements
Name peak attributes, use meat skewers in templates or jsx
Performance:
SSR Reduces first screen loading events
v-once
v-memo
shallowRef or
shallowReactive Reduce overhead
mutation is used to modify
stateaction
is used to submit a
mutation, and
action Can include asynchronous operations
Store storage global Status
commit({type, payload}),
dispatch(type, payload)
To implement Store
, you can define the Store
class, the constructor accepts options options
, and sets the properties state
Exposed status to the outside world, providing commit
and dispatch
modification attributes. Here you need to set state
as a responsive object, and define Store
as a Vue
plug-in (install method).
commit
You can get the user's incoming mutations
and execute it, so that the status can be modified according to the method provided by the user. dispatch
is similar, butdispatch
needs to return a Promise
to the user for processing asynchronous results.
(Learning video sharing: vuejs introductory tutorial, Basic programming video)
The above is the detailed content of [Compilation and summary] 45+ Vue interview questions to help you consolidate your knowledge points!. For more information, please follow other related articles on the PHP Chinese website!