This is the 12th day of my participation in the August Text Challenge.More challenges in August
In this article we will take a look at the built-in keep-alive and slot components and what to look for when using them.
keep-alive
When
wraps dynamic components, it caches inactive component instances rather than destroying them. Like
is an abstract component: it does not render a DOM element on its own, nor does it appear in the component’s parent chain.
is used for component caching because we need to use
when switching to a component that has already been displayed and we don’t want that component to re-render.
How to use
The basic use
can be used in conjunction with < Component > as follows:
<keep-alive>
<component :is="view"></component>
</keep-alive>
Copy the code
The
condition can be used in combination with V-if, V-else -if, and V-else.
<keep-alive>
<comp-a v-if="a > 1"></comp-a>
<comp-b v-else></comp-b>
</keep-alive>
Copy the code
Use with transitions or animation effects
can be used with
<transition>
<keep-alive>
<component :is="view"></component>
</keep-alive>
</transition>
Copy the code
This can be used when we need to switch components frequently with transitions or animations. It is worth noting that
is used when one of its immediate children has been switched. If you have v-for in it, it won’t work. If there are multiple conditional child elements,
requires that only one child element be rendered at a time.
Keep – Props of the alive
Include and exclude
Include and Exclude Prop allow components to cache conditionally. Include and exclude exclude. Both can be represented as comma-delimited strings, regular expressions, or an array.
- Comma-separated string
<keep-alive include="a,b">
<component :is="view"></component>
</keep-alive>
Copy the code
- Regular expression is required
v-bind
<keep-alive :include="/a|b/">
<component :is="view"></component>
</keep-alive>
Copy the code
- An array that needs to be used
v-bind
<keep-alive :include="['a', 'b']">
<component :is="view"></component>
</keep-alive>
Copy the code
Exclude is also used in the same way, matching the component’s name preferentially or its local registered name (the key of the parent component’s components option) if the name option is not available.
max
Maximum number of cached components. If this number is exceeded, those that have not been accessed for the longest time will be destroyed. Use as follows:
<keep-alive :max="10">
<component :is="view"></component>
</keep-alive>
Copy the code
slot
The
element acts as a content distribution slot in the component template, and the
element itself is replaced. In this article, we look back at the Vue3 directive (8), and discuss the use of slot as well as v-slot.
conclusion
-
you can use include and exclude to cache on demand.
-
The named and scoped slots of slot should be used properly.
For more articles, the portal has opened: Look back at the Vue3 catalogue!