Home  >  Q&A  >  body text

Return component in beforeEnter in vue router

I have the following path in my router

{
                path: '/Page',
                component: async () => {
                    const isUserLogged = await getUser()
                    const store = useStore()
                    if (userLogged && store.value1) {
                        return import('./pages/PublicPage/PublicPage.vue')
                    } else {
                        return import('./pages/NonPublicPage/NonPublicPage.vue')
                    }
                },
            },
}

Every time I enter this path, I need to return a different component based on the value in the store, but the component is only loaded once. I tried rewriting the structure so that it uses beforeEnter like this:

{
path: '/Page',
beforeEnter: async (to, from, next) => {
                    const isUserLogged = await getUser()
                    const store = useStore()
                    if (userLogged && store.value1) {
                            next({
                                component: () => import('./pages/PublicPage/PublicPage.vue'),
                            })
                    } else {
                        next({
                            component: () => import('./pages/NonPublicPage/NonPublicPage.vue'),
                        })
                    }
                },
}

But this solution doesn't work. Without using different paths, I need to return different components based on a condition. Is it possible to return a component in next() in beforeEnter or is there any other solution to solve this problem?

P粉787806024P粉787806024282 days ago339

reply all(1)I'll reply

  • P粉404539732

    P粉4045397322024-01-11 16:41:54

    I recommend using dynamic components.

    A simple solution is shown below.

    Your Router

    {
      path: '/Page',
      component: ConditionalPage
    }

    ConditionalPage.vue

    <script setup lang="ts">
    import { computed } from "vue"  
    import PublicPage from "./PublicPage.vue"  
    import NonPublicPage from "./NonPublicPage.vue"  
    
    const isUserLogged = await getUser()  
    const store = useStore()
    
    const component = computed(() => {
      if (userLogged && store.value1) return PublicPage
      return NonPublicPage
    })
    </script>
     
    <template>
      <component :is="component" />
    </template>

    Here is a more detailed example based on your code.

    Vue SFC Playground

    reply
    0
  • Cancelreply