【问题标题】:How to navigate to error page from Nuxt store如何从 Nuxt 商店导航到错误页面
【发布时间】:2021-10-31 12:03:04
【问题描述】:
export const state = () => ({
  data: {}
})

export const getters = {
  data: state => state.data
}

export const actions = {
  getData ({ commit }) {
    this.$axios('https://jsonplaceholder.typicode.com/todosx/1')
      .then((response) => {
        commit('SET_DATA', response.data)
      })
      .catch((err) => {
          // Navigate to error page
      })
  }
}

export const mutations = {
  SET_DATA (state, data) {
    state.data = data
  }
}

在 axios 的 catch 中捕获错误后,想从 Nuxt 商店 导航到错误页面。实现这一目标的最佳方法是什么?

【问题讨论】:

  • this.$router.push('/404') 应该可以解决问题,因为它要么存在,要么将使用 error 布局,因为它无法到达页面。
  • 顺便说一句,您可以在模板中使其更流畅并显示“此处无信息”而不是将用户移动到 404,您不觉得吗?
  • 感谢您的回复。是的,想在此处显示自定义错误模板。因此,可以像在页面中一样发送类似 $nuxt.error({ statusCode: 404, message: 'err message' }) 的内容。我试图在商店里做同样的事情,但不知道该怎么做。

标签: vue.js axios nuxt.js vuex


【解决方案1】:

在您的catch 中,您可以通过

将用户重定向到错误页面
return this.$nuxt.error({ statusCode: 404, message: 'Your error message' })

在您的error.vue 页面中,您可以使用错误道具访问它,例如:

<h1>{{ error.statusCode }}</h1>
<h2>{{ error.message }} </h2>

【讨论】:

  • 感谢您的回复。它确实在页面中工作,但在 vuex 存储中它给了我另一个错误 TypeError: Cannot read properties of undefined (reading 'error')。打印 this.$nuxt 时显示 undefined。有什么方法可以在 vuex 商店中访问 this.$nuxt 吗?
【解决方案2】:

这种模板应该可以在 $nuxt.error 之上正常工作

<template>
  <div class="container">
    <h1 v-if="error.statusCode === 404">Page not found</h1>
    <h1 v-else>An error occurred</h1>
    <NuxtLink to="/">Home page</NuxtLink>
  </div>
</template>

<script>
export default {
  props: ['error'],
}
</script>

如文档所示:https://nuxtjs.org/docs/2.x/directory-structure/layouts#error-page

【讨论】:

    猜你喜欢
    • 2021-12-31
    • 2020-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多