【问题标题】:Difficulty Redirecting to a 404 Page难以重定向到 404 页面
【发布时间】:2020-08-25 02:08:47
【问题描述】:

如果访问的用户配置文件不存在,我会尝试重定向到 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 页面?

【问题讨论】:

    标签: javascript vue.js vue-router


    【解决方案1】:

    使用beforeRouteEnterin-component navigation guard

    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
    }
    

    另见Data Fetching - Fetching Before Navigation

    请注意,无法通过 beforeRouteEnter 保护中的 this 访问 Vue 组件,因此您需要从定义的任何位置导入您的 store

    【讨论】:

    • 谢谢。这比 router.beforeEach 有什么优势?
    • @Matt 全局导航守卫在每次路线更改时执行,无论是哪条路线。它们是全局逻辑(如身份验证检查)的好地方,但我认为您上面的用例非常特定于这个特定组件
    【解决方案2】:

    我的建议是您应该使用router.beforeEach 将逻辑放入global before guards

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-05
      • 2023-03-27
      相关资源
      最近更新 更多