javascript / intermediate
Snippet
Dynamic Component Switching with shallowRef
Using shallowRef for dynamic components is a performance best practice in Vue. Unlike ref, shallowRef only tracks the .value property itself, preventing Vue from recursively making the entire component instance reactive, which is unnecessary and expensive.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<script setup>import { shallowRef } from 'vue';import AdminView from './AdminView.vue';import UserView from './UserView.vue';const activeView = shallowRef(AdminView);const toggleView = () => {activeView.value = activeView.value === AdminView ? UserView : AdminView;};</script><template><component :is="activeView" /><button @click="toggleView">Switch View</button></template>
vue
Breakdown
1
const activeView = shallowRef(AdminView);
Creates a shallow reactive reference to the component constructor.
2
<component :is="activeView" />
The built-in dynamic component that renders whatever is assigned to activeView.