vue-router对于存在但没有关联记录的路径报告404错误。

huangapple go评论60阅读模式
英文:

vue-router 404 errors for paths that exist but do not have an associated record

问题

以下是翻译好的内容:

My project is using vue-router and I am looking for a good way to handle 404 errors for paths that exist in my routes.js but doesn't have an associated record.

For example if someone visits:

https://localhost/tutorials/how-to-train-a-chimpanzee

The router finds the tutorials/:slug but after we query the api the results come back with 404.

What I would like to do is have a generic 404 page display and keep the current url.

There is a boat ton of documentation around generic 404s with vue-router. I can't find much about this specific use case. Any guidance would be appreciated.

This below approach is working in our app. The code below is heavily edited so it might contain errors.

src/routers/routes.js

const routes = [
  {
    path: '/',
    component: () => import('layouts/MainLayout.vue'),
    children: [
      { path: '', component: () => import('pages/IndexPage.vue') },
      {
        name: 'tutorial',
        path: '/tutorials/:slug',
        props: true,
        component: () => import('pages/Tutorial.vue'),
      },
    ],
  },

  {
    path: '/:catchAll(.*)*',
    component: () => import('pages/ErrorNotFound.vue'),
  },
];

export default routes;

src/store/tutorials/action.js

const show = (context, data) => {
  return new Promise((resolve, reject) => {
    ProfileService.show(data)
      .then((response) => {
        context.commit('tutorials/setModel', { model: e.tutorial })
        // Do other stuff
        resolve(response)
      })
      .catch((error) => {
        console.log(error)
        reject(error)
      })
  })
}

src/pages/Tutorial.vue

const fetchData = () => {
  store.dispatch('tutorials/show', { slug: route.params.slug })
    .then(response => {
      // do more stuff
    })
    .catch(error => {
      router.push('/error-404')
    })
}
英文:

My project is using vue-router and I am looking for a good way to handle 404 errors for paths that exist in my routes.js but doesn't have an associated record.

For example if someone visits:

https://localhost/tutorials/how-to-train-a-chimpanzee

The router finds the tutorials/:slug but after we query the api the results come back with 404.

What I would like to do is have a generic 404 page display and keep the current url.

There is a boat ton of documentation around generic 404s with vue-router. I can't find much about this specific use case. Any guidance would be appreciated.

This below approach is working in our app. The code below is heavily edited so it might contain errors.

src/routers/routes.js

const routes = [
  {
    path: '/',
    component: () => import('layouts/MainLayout.vue'),
    children: [
      { path: '', component: () => import('pages/IndexPage.vue') },
      {
        name: 'tutorial',
        path: '/tutorials/:slug',
        props: true,
        component: () =>
	      import('pages/Tutorial.vue'),
        }
    ]
  },

  {
    path: '/:catchAll(.*)*',
    component: () => import('pages/ErrorNotFound.vue')
  }
]

export default routes

src/store/tutorials/action.js

const show = (context, data) => {
  return new Promise((resolve, reject) => {
    ProfileService.show(data)
      .then((response) => {
        context.commit('tutorials/setModel', { model: e.tutorial })
        // Do other stuff
        resolve(response)
      })
      .catch((error) => {
        console.log(error)
        reject(error)
      })
  })
}

src/pages/Tutorial.vue

const fetchData = () => {
	store.dispatch('tutorials/show', { slug: route.params.slug })
	.then(response => {
		// do more stuff
	})
	.catch(error => {
		router.push('/error-404')
	})
}

答案1

得分: 1

我所做的是在beforeEnter守卫中获取我的数据。 如果返回值指示数据不存在,我会重定向到不同的页面(首页、404页面等)。否则,导航会继续进行,在这一点上,我的存储也已经具有所需的数据,组件不再需要调用fetch本身。

英文:

What I do is fetch my data in a beforeEnter guard. If the return value indicates the data does not exist, I reroute to a different page (home page, 404 page, etc.). Otherwise navigation continues, at which point my store also already has the data it needs and the component no longer needs to call the fetch itself.

{
  name: 'tutorial',
  path: '/tutorials/:slug',
  props: true,
  beforeEnter: async (to) => {
    const route = await store.dispatch('tutorials/show', { slug: to.params.slug })
      .then((res) => {
        if (res.data) return true; // continue navigation
      })
      .catch(() => {
        return { path: "/error-404" };
      });
    return route
  }
}

huangapple
  • 本文由 发表于 2023年5月24日 23:55:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/76325389.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定