如何在带有404页面的动态url上使用vue js 3路由?

问题描述 投票:0回答:1

我有单页网站,即 xyz.com,在此页面中我正在检查一些动态网址和 404 页面的路由。

当我访问 xyz.com/p1xyz.com/p2...等网址时。路由按预期工作,但当访问任何无效网址(如 xyz.com/invalid)时,它会在 NotFound 组件上正确重定向,但同时会更新网址。

例如:如果我访问xyz.com/invalid,则网址会更改fromxyz.com/invalidtoxyz.com.

  1. 如果有人访问无效的 url,我如何保留 url,并且它应该重定向到 NotFound 组件,即 404 页面。

  2. 如果我访问像 xyz.com/invalid/ 这样的网址(在末尾添加额外的斜杠)那么它会显示空白页面而不是 NotFound 页面?理想情况下,第一个斜杠之后的任何内容都应该重定向到 NotFound 页面。

  3. 有什么帮助吗?

以下是代码片段:

main.js:

注意:

productArray 包含“n”个。的产品。 var productArray = [ { label: "product1", code: "p1", }, { label: "product2", code: "p2", }, { label: "product3", code: "p3", } ]; const routes = [{ path: "/:product", component: Home, beforeEnter(to, from, next) { const item = to.params.lang; if (productArray.find((e) => e.code == product) == undefined) { next({ name: "notFound"}); } else { return next(); } }, }, { path: "/:pathMatch(.*)*", name: "notFound", component: NotFound, }, { path: "/", redirect: 'p1', }, ]; const router = createRouter({ history: createWebHistory(), routes, }); let app = createApp(App); app.use(router); app.mount("#app");


vue.js vuejs3 vue-router vue-router4
1个回答
0
投票
params

 中包含的 
next
 属性保留当前路径
next({ name: 'notFound', params: { pathMatch: to.path.substring(1).split('/') } })

© www.soinside.com 2019 - 2024. All rights reserved.