难以重定向到404页面

3
我将尝试将用户访问的个人资料不存在时重定向到404页面。 我运行一个异步创建的生命周期钩子,检查用户是否存在,如果不存在,我使用$router.push来推送到404页面,代码如下:

component.vue

async created() {
    const userExists = await this.$store.dispatch("user/creatorExists", {
        userId: this.$route.params.userId
    });
    if (!userExists) {
        this.$router.push({ name: "pageNotFound" });
    }

问题在于在检查用户是否存在的调用期间,component.vue将完全加载,因此最终用户将在被重定向之前看到初始组件闪烁在屏幕上。

如果用户不存在,是否有更好的方式来重定向到404页面?
2个回答

1

使用beforeRouteEnter 组件内导航守卫

import store from "wherever/your/store/lives"

export default {
  name: "UserProfile",
  async beforeRouteEnter (to, from, next) {
    const userExists = await store.dispatch("user/creatorExists", {
        userId: to.params.userId
    });
    if (!userExists) {
        return next({ name: "pageNotFound" });
    }
    next()
  },
  // data, computed, methods, etc
}

另请参阅 数据获取-导航前获取

请注意,在 beforeRouteEnter 守卫中无法通过 this 访问Vue组件,因此您需要从定义位置导入 store


谢谢。这个有什么优势,胜过于router.beforeEach吗? - Matt
2
@Matt 全局导航守卫会在每次路由变化时执行,无论是哪个路由。它们是全局逻辑(如身份验证检查)的好地方,但我认为你上面提到的用例非常特定于这个特定组件。 - Phil

1
我的建议是,在全局守卫之前使用router.beforeEach来放置逻辑。
const router = new VueRouter({ ... })

router.beforeEach((to, from, next) => {
 // Check each time before entering the page or a specific page  
})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接