0 day streak
javascript / intermediate
Snippet

Dynamic Component Switching with Object Mapping

Instead of using long v-if/v-else chains, using the <component> element with a dynamic :is binding and an object map is a cleaner, more scalable intermediate pattern for conditional rendering.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<script setup>
import AdminView from './AdminView.vue';
import UserView from './UserView.vue';
import GuestView from './GuestView.vue';
const roleMap = {
admin: AdminView,
user: UserView,
guest: GuestView
};
const userRole = ref('user');
</script>
<template>
<component :is="roleMap[userRole]" />
</template>
vue
Breakdown
1
const roleMap = { ... }
Maps keys to component definitions for O(1) lookup.
2
<component :is="roleMap[userRole]" />
Vue's built-in element to render components based on a variable.