Return component in beforeEnter in vue router
P粉787806024
P粉787806024 2024-01-10 17:51:45
0
1
337

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粉787806024
P粉787806024

reply all(1)
P粉404539732

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!