【问题标题】:using `$router.push` when validating a dynamic route在验证动态路由时使用“$router.push”
【发布时间】:2020-07-02 14:07:57
【问题描述】:

我正在使用 Nuxt,并且我创建了一个动态路由,该路由使用 vuex 和 axios 调用获取数据。当没有指定 id 参数时,我想将用户路由回index。我看到我可以在动态路由上使用validate https://nuxtjs.org/api/pages-validateWhen

我正在使用下面的代码,当我导航到 localhost:3000/settings/ 时,我收到以下错误 Cannot read property 'push' of undefined

页面/设置/_id.vue

export default {  
  validate({ params }) {
    if (params.id !== null) {
      this.$router.push({ name: 'index' })
    }
    return false
  }
}

【问题讨论】:

    标签: vue.js vuejs2 nuxt.js


    【解决方案1】:

    每次导航到新路线之前都会调用验证。它将被称为服务器端一次。这意味着在创建组件之前执行验证。所以你不能访问 this.$router 因为此时这个不存在。

    查看 Fetch Hook 和 Nuxt Lifecycle 以获得更好的解释: https://nuxtjs.org/blog/understanding-how-fetch-works-in-nuxt-2-12/#fetch-hook-and-nuxt-lifecycle

    基本上,我们需要做的是从 nuxt 上下文中导入重定向和路由,以便在现场或验证功能中使用它。 ROUTE 包含有关您的请求的所有信息,重定向是来自 nuxt 的函数,用于中间件内部。

    我为你创建了一个例子:

    <template>
      <v-row>
        <v-col cols="12">
          <pre>
            {{ params }}
          </pre>
        </v-col>
      </v-row>
    </template>
    
    <script>
    export default {
      data() {
        return {
          params: []
        }
      },
      validate({ redirect, route }) {
        if (route.params) {
          // eslint-disable-next-line no-console
          console.log('RouteParams:', route.params)
          this.params = route.params
        }
        redirect({ name: 'index' })
        // return false
      }
    }
    </script>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-04
      • 1970-01-01
      • 2021-06-08
      • 1970-01-01
      • 1970-01-01
      • 2018-02-28
      相关资源
      最近更新 更多