[英]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.