【问题标题】:How to create 404 page on dynamic routes Nuxt js Fetch method如何在动态路由 Nuxt js Fetch 方法上创建 404 页面
【发布时间】:2022-11-11 09:11:22
【问题描述】:

我有动态路由http://localhost:3000/sections/slug-name。如果 URL 无效,我想显示或重定向到 404 页面。尝试使用 fetch 方法做类似this 的事情。

我知道我们可以做到 <p v-if="$fetchState.error">404 Invalid Section</p>,但有没有更好的方法来显示 404 页面。

以下是我的代码供您参考

<script>
export default {
  data() {
    return {
      posts: {},
      loader: false,
    }
  },
  head() {
    return {
      title: this.posts.category_name ,

    }
  },
 

  methods: {
    getResults(page = 1) {
      if (this.$route.query.page != page) {
        this.$router.push({
          query: {
            page: page,
          },
        })
      }
    },

    loadPosts(page) {
      this.loader = true
      this.$axios
        .$get(`category/${this.$route.params.category}?page=${page}`)
        .then((response) => {
          this.posts = response
          this.loader = false
        })
    },
  },
  watch: {
    $route(to, from) {
      this.loadPosts(to.query.page)
    },
  },
  async fetch() {
    let page = this.$route.query.page ? this.$route.query.page : 1
    this.posts = await this.$axios
      .$get(`category/${this.$route.params.category}?page=${page}`)
      .catch((e) => {
        this.$router.push({ name: 'fallback-page' })
      })
  },
}
</script>

【问题讨论】:

    标签: vue.js nuxt.js


    【解决方案1】:

    更新:如我的answer here 所示,如果您在使用fetch() 钩子时想要相同的行为,可以使用它

    this.$nuxt.context.error({
      status: 500,
      message: 'Something bad happened',
    })
    

    由于您使用的是 SSR,因此下面的部分大多是错误的。

    如果您没有特定路径的路线,您可以设置这个

    nuxt.config.js

    export default {
      generate: {
        fallback: '404.html',
      },
    }
    

    并创建一个/layouts/error.vue 文件

    <template>
      <p>some error here {{ error }}</p>
    </template>
    
    <script>
    export default {
      props: ['error'],
    }
    </script>
    

    以这种方式,如果您到达/hello-word 而它在您的路线中不存在,您将回退到这个。

    正如herehere 所解释的那样。


    如果您希望在获取后进行客户端重定向,您总是可以有一个

    .catch((e) => {  this.$router.push({ name: 'fallback-page' })  })
    

    catch 之后。

    【讨论】:

    • 嘿,我不能使用$router.push,因为我使用的是 fetch 方法,它似乎首先渲染组件,这就是我得到Cannot read property 'category_name' of undefined 的原因
    • @KunalRajput 这是其他问题。你的模板是同步的,如果你有类似object.category_nameobject 是异步的,它会抛出这个错误。与 404 无关。完成 API 调用后,将模板包装到 $fetchState.pending 中,然后显示模板的其余部分。
    • 是的,在 head() 我正在使用 title: this.post.category_name ,我如何在 head 方法中使用 fetchState.pending
    • @KunalRajput 我已经用您正在寻找的内容更新了我的初始答案(关于fetch() 钩子)。同时,关于 SEO 的事情,这是一个完全不相关的问题。我已经回答了similar here
    • 我没有使用 SSG,我最终为此使用了 asynData 并且它有效。谢谢你再次救了我
    【解决方案2】:

    您必须在 catch 的 fetch 或 asyncData 方法中使用 error({ statusCode: 404}) 将客户端重定向到 404 页面

    【讨论】:

    • client.js?06a0:56 fetch() 中的错误:ReferenceError:错误未定义
    • 把你写的代码准确地引导你
    • 我已经用代码更新了问题
    猜你喜欢
    • 2023-03-13
    • 2022-11-15
    • 2020-01-27
    • 2019-07-20
    • 2021-06-16
    • 2020-11-18
    • 2023-03-21
    • 1970-01-01
    • 2023-03-11
    相关资源
    最近更新 更多