Vue.JS - “历史”和“抽象”路由器?

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

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

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

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

我还希望即使在完成表单后也可以访问此URL,因此不幸的是,这里的摘要不是一个选项。

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

javascript vue.js vuex router
2个回答
1
投票

你不能做这个。它既可以是历史的,也可以是抽说完这个,你可以做几件事。

Approach 1: Use history mode with steps as query params

因此,不要使用像/step-1/step-2这样的路线,而是将其作为查询参数的一部分。所以你会有以下路线:

  • 指数路线:example.com/?step=1example.com/?step=2
  • 结果路线:example.com/result/:userId

Approach 2: Use abstract mode with higher order component

在这里,您将拥有一个带抽象的路由器,但它只能用作状态路由器,并且无助于任何浏览器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');
        }
    }

}

Approach 3: Use Multi-page SPA

在这里,您将创建两个单页面应用程序。第一个应用程序将具有路线/step-1/step-2等。您将使用抽象模式。第二个应用程序将具有历史模式的/result/:userId路由。

在此体系结构中,当用户使用step-5时,您将使用HTML5历史记录API来更改路由器,然后导致强制页面刷新,而不是将新状态推送到路由器。此外,还有其他方法可以实现这一目标。


0
投票

你可以简单地在原生javascript中进行重定向,你可以将其称为window.location.href('yourHomePage.com'),它将完全刷新。

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