javascript - Vue.JS - “历史”和“抽象”路由器?
问题描述
我正在创建一个用户填写 5 步表单的 VueJS 应用程序。
这些步骤在 Vue Router 中被路由到/step-1
through 。/step-5
但是,我希望网站/
在刷新页面时返回到索引页面 ( )。
我可以abstract
为此使用模式——但结果页面是从以下 url 生成的:/result/:userid
我需要在其中的状态才能history
从 URL 获取用户 ID(然后向服务器发出 post 请求)。
我还希望即使在完成表单之后也可以访问这个 URL,所以很遗憾,这里的抽象不是一个选项。
那么——是否可以同时使用这两种模式?刷新index.html
表单页面时刷新页面,然后使用history
模式呈现结果?
解决方案
你不能做这个。它要么是历史的,要么是抽象的,但不是两者兼而有之。话虽如此,您可以做几件事。
方法一:使用history
带步骤的模式作为查询参数
/step-1
因此,不要使用or之类的路由/step-2
,而是使用 then 作为查询参数的一部分。所以你会有这样的路线:
- 索引路线:
example.com/?step=1
,example.com/?step=2
- 结果路线:
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');
}
}
}
方法 3:使用多页 SPA
在这里,您将创建两个单页应用程序。第一个应用程序将具有 routes /step-1
、/step-2
等。您将为此使用抽象模式。第二个应用程序将具有历史模式的/result/:userId
路由。
在这种架构中,当用户打开时step-5
,您将使用 HTML5 历史 API 更改路由器,然后导致强制页面刷新,而不是向路由器推送新状态。此外,还有其他方法可以实现这一目标。
推荐阅读
- php - 多个页面上的多个 URL 重定向
- python - 通过多个变量的模糊匹配来匹配实体
- maven - 在 2 个不同的关系上部署人工制品
- c# - Thrift 如何处理被拆分为多个消息的 Zlib 刷新标记?
- ios - XCode 导致 App Fabric 崩溃
- javascript - 如何使用正则表达式更改文本中的单词颜色 - Javascript
- html - 如何使用引导程序 3 将文本与背景图像的底部对齐
- powershell - Powershell 模块 GUID
- youtube-dl - 如何将 WebVTT 格式转换为纯文本?
- reactjs - 如何保存 Formik 中每个切换字段的值?