首页 > 解决方案 > Vue.JS - “历史”和“抽象”路由器?

问题描述

我正在创建一个用户填写 5 步表单的 VueJS 应用程序。

这些步骤在 Vue Router 中被路由到/step-1through 。/step-5但是,我希望网站/在刷新页面时返回到索引页面 ( )。

我可以abstract为此使用模式——但结果页面是从以下 url 生成的:/result/:userid我需要在其中的状态才能history从 URL 获取用户 ID(然后向服务器发出 post 请求)。

我还希望即使在完成表单之后也可以访问这个 URL,所以很遗憾,这里的抽象不是一个选项。

那么——是否可以同时使用这两种模式?刷新index.html表单页面时刷新页面,然后使用history模式呈现结果?

标签: javascriptvue.jsvuexrouter

解决方案


你不能做这个。它要么是历史的,要么是抽象的,但不是两者兼而有之。话虽如此,您可以做几件事。

方法一:使用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 更改路由器,然后导致强制页面刷新,而不是向路由器推送新状态。此外,还有其他方法可以实现这一目标。


推荐阅读