如何在 Nuxt 的 asyncData 中重定向

hoo*_*vhd 3 vue.js vue-router vue-component vuejs2 nuxt.js

我是 vue.js 的新手,我有一个简单的问题。

我有如下代码:

  asyncData({ params, error }) {
    return Job.api()
      .fetchByID(params.id)
      .then((response) => {
        const selectedJob = response.entities.jobs[0]
        if (selectedJob) {
          const industryID = selectedJob.industryId
          return Industry.api()
            .fetchByID(industryID)
            .then((result) => {
              const jobInd = result.response.data
              return {
                tagsArray:
                  selectedJob.tags === 'null' || selectedJob.tags === ''
                    ? []
                    : selectedJob.tags.split(','),
                job: selectedJob,
                jobIndustry: jobInd,
              }
            })
            .catch(() => {
              error({
                statusCode: 404,
                message: 'Job Industry not found',
              })
            })
        }
      })
      .catch(() => {
        error({
          statusCode: 404,
          message: 'Job not found',
        })
      })
  },
Run Code Online (Sandbox Code Playgroud)

我想知道在捕获404错误后如何将页面重定向到主页。

ton*_*y19 6

asyncData()的参数是Nuxt context,其中包括redirect()您可以用来重定向用户的内容:

export default {
  asyncData({ redirect, params, error }) {
    return Job.api()
      .fetchByID(params.id)
      .then(/*...*/)
      .catch(() => {
        redirect('/')
      })
  }
}
Run Code Online (Sandbox Code Playgroud)