代码之家  ›  专栏  ›  技术社区  ›  Matt

难以重定向到404页

  •  3
  • Matt  · 技术社区  · 5 年前

    $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" });
        }
    

    问题是在呼叫检查用户是否存在的过程中, 组件.vue 将完全加载,因此最终用户将在重定向之前看到屏幕上的初始组件闪烁。

    2 回复  |  直到 5 年前
        1
  •  1
  •   Phil    5 年前

    使用 beforeRouteEnter in-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

    this 在例行检查之前 所以你需要导入 store 从任何定义它的地方。

        2
  •  1
  •   sugars    5 年前

    我的建议是你应该在 global before guards router.beforeEach

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