Consider a Vue 3 app where a component is wrapped inside a
<template>
<keep-alive>
<ExpensiveComponent v-if="show" />
</keep-alive>
</template>
<script setup>
import { ref } from 'vue'
import ExpensiveComponent from './ExpensiveComponent.vue'
const show = ref(true)
</script>Think about what
Wrapping a component with
In Vue 3, if a component wrapped in
<script setup> import { onMounted, onUnmounted, onActivated, onDeactivated } from 'vue' onMounted(() => console.log('mounted')) onUnmounted(() => console.log('unmounted')) onActivated(() => console.log('activated')) onDeactivated(() => console.log('deactivated')) </script>
Remember that
When a deactivated hook instead of unmounted. When shown again, it triggers activated. The mounted hook runs only once when first created.
Choose the correct syntax to cache only components named 'ExpensiveComponent' and 'HeavyWidget' using
<template> <keep-alive :include="['ExpensiveComponent', 'HeavyWidget']"> <component :is="currentComponent" /> </keep-alive> </template>
Check how to bind props dynamically in Vue templates.
The include prop expects a string or an array. To pass an array, use the binding syntax :include with an array value. Option A correctly uses :include with an array.
A developer wraps a component with
<template>
<keep-alive>
<ExpensiveComponent v-if="show" :key="uniqueKey" />
</keep-alive>
</template>
<script setup>
import { ref } from 'vue'
const show = ref(true)
const uniqueKey = ref(1)
</script>Think about how Vue uses keys to identify components.
When the :key changes, Vue treats the component as a new instance and recreates it, ignoring the cached version. This causes the state to reset despite
Explain the main reason why using
Think about what happens when a component is removed and added back without caching.