[英]Vue.JS - Both 'history' and 'abstract' router?
我正在创建一个 VueJS 应用程序,用户可以在其中填写一个 5 步表单。
这些步骤被路由到 Vue Router 中的/step-1
到/step-5
。 但是,我希望网站在刷新页面时返回到索引页面 ( /
)。
我可以为此使用abstract
模式 - 但结果页面是从以下 URL 生成的: /result/:userid
其中我需要状态是history
以便能够从 URL 获取用户 ID(然后执行向服务器发送请求)。
我还希望即使在完成表单后也可以访问此 URL,因此不幸的是,这里的抽象不是一个选项。
那么 – 是否可以同时使用这两种模式? 刷新表单页面时将页面刷新为index.html
,然后使用history
模式呈现结果?
你不可以做这个。 它要么是历史的,要么是抽象的,但不能两者兼而有之。 话虽如此,您可以做几件事。
history
模式和步骤作为查询参数因此,不要使用像/step-1
或/step-2
这样的路由,而是将 then 用作查询参数的一部分。 所以你会有这样的路线:
example.com/?step=1
, example.com/?step=2
example.com/result/:userId
: example.com/result/:userId
abstract
模式在这里,您将拥有一个带有抽象的路由器,但它仅用作状态路由器,不会帮助处理任何浏览器 URL 操作。
构建一个像AppComponent
这样的高阶组件,您将在其中使用自己的正则表达式来确定路由。 它看起来像:
// Should match route /result/:userId
const IS_RESULT = new RegExp('/result/(\\d+)$');
// User RegExp groups
const IS_STEP = new RegExp('/step-(\\d+)$');
export default class AppComponent extends Vue {
// Use Vue.js created hook
created() {
const path = window.location.pathname;
// Top level routing of the application
if (IS_STEP.test(path)) {
// Do something. You are in step-1/step-2/etc.
} if (IS_RESULT.test(path)) {
// Do something. You are in /result/:userId
// Get userId
const groups = IS_RESULT.exec(path);
const userId = groups[1];
} else {
// Goto Error page
throw new Error('Unknown route');
}
}
}
在这里,您将创建两个单页应用程序。 第一个应用程序将包含路由/step-1
、 /step-2
等。您将为此使用抽象模式。 第二个应用程序将具有历史模式的/result/:userId
路由。
在这种架构中,当用户处于step-5
,您将使用 HTML5 历史 API 更改路由器,然后强制页面刷新,而不是将新状态推送到路由器。 此外,还有其他方法可以实现这一点。
您可以简单地在原生 javascript 中进行重定向,您将其命名为 window.location.href('yourHomePage.com'),它会进行完全刷新。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.