Vue Router - 相同的路径,不同的组件

发布于 2025-01-15 05:24:00 字数 1161 浏览 0 评论 0原文

在 Vue Router 中,我想基于变量在同一路径中显示不同的组件。

如果 isFirstTimeAccess 为 true,我想显示欢迎组件,如果为 false,我想在浏览器上的同一路径中显示 AuthHandler 组件 -> /my-sub-url/

示例:

export const router = createRouter({
    history: createWebHistory(),
    routes: [{
            path: '/my-sub-url/',
            component: welcome,
            beforeEnter(to, from, next) {
                if (store.getters.isFirstTimeAccess) {
                    next();
                } else {
                    next({
                        name: 'auth'
                    });
                }
            },
            children: [{
                    name: 'auth',
                    path: '',
                    component: AuthHandler,
                },
            ]
        }
    ];
});

但是如果我尝试此代码,如果我设置:

  • isFirstTimeAccess === true ->它可以工作并显示欢迎组件

  • isFirstTimeAccess === false ->它在浏览器中向我显示此错误:

[Vue Router warn]:从“/”转到“/my-sub-url/”时在导航防护中检测到无限重定向。中止以避免堆栈溢出。如果不修复,这将导致生产中断。 vue-router.esm-bundler.js:72

[Vue Router warn]: 启动路由器时出现意外错误:错误:导航防护中无限重定向

有人可以帮助我吗?

In Vue Router I want to show different components in the same path, based on a variable.

If isFirstTimeAccess is true i want to show Welcome Component, if it is false I want to show AuthHandler component in the same path on the browser -> /my-sub-url/

Example:

export const router = createRouter({
    history: createWebHistory(),
    routes: [{
            path: '/my-sub-url/',
            component: welcome,
            beforeEnter(to, from, next) {
                if (store.getters.isFirstTimeAccess) {
                    next();
                } else {
                    next({
                        name: 'auth'
                    });
                }
            },
            children: [{
                    name: 'auth',
                    path: '',
                    component: AuthHandler,
                },
            ]
        }
    ];
});

but If i tried this code if I set :

  • isFirstTimeAccess === true -> it works and show the welcome component

  • isFirstTimeAccess === false -> it show me this error in browser:

[Vue Router warn]: Detected an infinite redirection in a navigation guard when going from "/" to "/my-sub-url/". Aborting to avoid a Stack Overflow. This will break in production if not fixed.
vue-router.esm-bundler.js:72

[Vue Router warn]: Unexpected error when starting the router: Error: Infinite redirect in navigation guard

Can someone help me please?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

乱世争霸 2025-01-22 05:24:00

试试这个方法

<template>
  <component :is="checkComponentAccess"></component>
</template>

<script>

export default {
  components: {
    WelcomeComponent: () => import("/path/to/component/WelcomeComponent"),
    SecondTimeComponent: () => import("/path/to/component/SecondTimeComponent")
  },
  computed: {
    ...mapGetters("user", ["isFirstTimeAccess"]),
    checkComponentAccess() {
      return this.isFirstTimeAccess === "citizen" ? "FirstComponent" : "SecondComponent";
    }
  }
};
</script>

Try this way

<template>
  <component :is="checkComponentAccess"></component>
</template>

<script>

export default {
  components: {
    WelcomeComponent: () => import("/path/to/component/WelcomeComponent"),
    SecondTimeComponent: () => import("/path/to/component/SecondTimeComponent")
  },
  computed: {
    ...mapGetters("user", ["isFirstTimeAccess"]),
    checkComponentAccess() {
      return this.isFirstTimeAccess === "citizen" ? "FirstComponent" : "SecondComponent";
    }
  }
};
</script>
静水深流 2025-01-22 05:24:00

这似乎是 Vue Router 的 导航守卫 的完美案例。他们甚至还有像您这样的身份验证案例的具体示例。

刚刚从那里复制:

router.beforeEach(async (to, from) => {
  if (
    // make sure the user is authenticated
    !isAuthenticated &&
    // ❗️ Avoid an infinite redirect
    to.name !== 'Login'
  ) {
    // redirect the user to the login page
    return { name: 'Login' }
  }
})

This seems to be a perfect case for Vue Router's navigation guards. They even have a specific example for an authentication case like yours.

Just copied from there:

router.beforeEach(async (to, from) => {
  if (
    // make sure the user is authenticated
    !isAuthenticated &&
    // ❗️ Avoid an infinite redirect
    to.name !== 'Login'
  ) {
    // redirect the user to the login page
    return { name: 'Login' }
  }
})
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文