Consider a Vue app where a component is wrapped inside a
<template>
<keep-alive>
<MyComponent v-if="show" />
</keep-alive>
</template>
<script setup>
import { ref } from 'vue'
import MyComponent from './MyComponent.vue'
const show = ref(true)
</script>Think about what caching means for a component's state and lifecycle.
Wrapping a component with created are not called again.
Given the component below, what will be the value of count after toggling show off and then on again?
<template>
<keep-alive>
<Counter v-if="show" />
</keep-alive>
<button @click="show = !show">Toggle</button>
</template>
<script setup>
import { ref } from 'vue'
import Counter from './Counter.vue'
const show = ref(true)
</script>
<!-- Counter.vue -->
<template>
<button @click="count++">Count: {{ count }}</button>
</template>
<script setup>
import { ref } from 'vue'
const count = ref(0)
</script>Remember what
Because the component is cached by count, is preserved when toggled off and on. The count does not reset.
Consider a component wrapped in
<template>
<keep-alive>
<MyComponent v-if="show" />
</keep-alive>
<button @click="show = !show">Toggle</button>
</template>
<script setup>
import { ref } from 'vue'
import MyComponent from './MyComponent.vue'
const show = ref(true)
</script>Think about the special lifecycle hooks activated and deactivated in Vue.
When using deactivated but is not destroyed. When toggled on again, it triggers activated. The created and mounted hooks do not run again.
You want to cache only components named 'Home' and 'Profile' using
Check how to bind props dynamically in Vue templates.
The include prop expects a string or an array of component names. To pass an array, you must bind the prop using :. Option D correctly binds an array of strings. Option D passes a string but without binding, so it is treated as a literal string. Options C and D have syntax errors.
You wrapped a component with
<template>
<keep-alive>
<MyComponent :value="parentValue" />
</keep-alive>
<button @click="parentValue++">Change Value</button>
</template>
<script setup>
import { ref } from 'vue'
import MyComponent from './MyComponent.vue'
const parentValue = ref(0)
</script>Consider how Vue tracks component identity and updates with
key on the component forces Vue to recreate it and update props.