Preface
Invuejs
, we often need to cache the status of some components. For example, after a user logs in, switches to other pages, and then switches back, the previous login status needs to be retained instead of restarting. Log in.
Or when switching between different components, you need to retain the previous component state instead of reloading. If you set nothing
You will find that all previously changed states have been reset.
It usually makes sense to create new component instances when switching, but in some cases we really want components to retain their state when being "switched away". To solve this problem, we can wrap these dynamic components with <KeepAlive>
built-in components
code example
<!-- 非活跃的组件将会被缓存! -->
<KeepAlive>
<component :is="activeComponent" />
</KeepAlive>
Include and exclude
<KeepAlive>
will cache all internal component instances by default, but we can control the components through include
and exclude
's prop
Caching or not caching. Both prop
values can be a comma-separated string, a regular expression, or an array containing both types
<!-- 以英文逗号分隔的字符串,a,b代表的是组件 -->
<KeepAlive include="a,b">
<component :is="view" />
</KeepAlive>
<!-- 正则表达式 (需使用 `v-bind`) -->
<KeepAlive :include="/a|b/">
<component :is="view" />
</KeepAlive>
<!-- 数组 (需使用 `v-bind`),如果有多个,可以用一个数组 -->
<KeepAlive :include="['a', 'b']">
<component :is="view" />
</KeepAlive>
It will be matched according to the component's name
option, so if the component wants to be conditionally cached by KeepAlive
, it must explicitly declare a < /span>name
option
Precautions
Single file components using<script setup>
will automatically generate the corresponding name
options based on the file name, no need to manually declare
Before front-end and back-end joint debugging - a front-end’s thoughts before hand-writing code
How to tell if a girl is a prude
vue3+vite installation element-plus error report solution - using components does not work
How does a VuePress website use axios to request a third-party interface?
Front-end and back-end development interface joint debugging and docking parameters
Implementing 3D panoramic room viewing in Vue