CodexBloom - Programming Q&A Platform

Vue 3: How to dynamically load components based on user permissions?

👀 Views: 416 đŸ’Ŧ Answers: 1 📅 Created: 2025-08-30
vue.js vuex vue-router JavaScript

I've been working on this all day and I'm working on a Vue 3 application where I need to conditionally render different components based on user permissions. For example, I want to show a `UserProfile` component for regular users and an `AdminDashboard` for admin users. I'm using Vue Router for navigation and Vuex for state management. However, the components don't seem to update based on the changes in permissions from Vuex. I've set up a store with the following state: ```javascript const store = new Vuex.Store({ state: { user: { role: 'guest', // can be 'user' or 'admin' } }, mutations: { setUserRole(state, role) { state.user.role = role; } } }); ``` In my App.vue, I try to conditionally load components like this: ```html <template> <div> <component :is="currentComponent" /> </div> </template> <script> export default { computed: { currentComponent() { const role = this.$store.state.user.role; return role === 'admin' ? 'AdminDashboard' : 'UserProfile'; } } } </script> ``` But the question is that even when I change the user role using the mutation like this: ```javascript this.$store.commit('setUserRole', 'admin'); ``` The UI does not update accordingly, and I see the old component continue. I've confirmed that the `currentComponent` computed property does indeed return the new component name. No errors are thrown, but the expected reactivity is missing. Is there something wrong with my setup, or is there a better way to handle dynamic components in Vue 3? Any insights would be appreciated! I appreciate any insights! This is my first time working with Javascript 3.9. Is there a better approach?