This example shows two counters. Switching between them keeps their counts because they are wrapped in <keep-alive>. The counters do not reset when you switch views.
<template>
<div>
<button @click="currentView = 'CounterA'">Show Counter A</button>
<button @click="currentView = 'CounterB'">Show Counter B</button>
<keep-alive>
<component :is="currentView" />
</keep-alive>
</div>
</template>
<script setup>
import { ref } from 'vue'
const currentView = ref('CounterA')
const CounterA = {
template: `<div>
<p>Counter A: {{ count }}</p>
<button @click="count++">Increment A</button>
</div>`,
data() {
return { count: 0 }
}
}
const CounterB = {
template: `<div>
<p>Counter B: {{ count }}</p>
<button @click="count++">Increment B</button>
</div>`,
data() {
return { count: 0 }
}
}
const views = { CounterA, CounterB }
// Register components globally or locally
defineExpose({ views })
</script>