我正在實施一個分頁串列。因此我使用查詢引數,如?size=10. 此查詢引數必須始終位于我的 URL 中(例如 /home?size=2)。
此方法不起作用:
const routes = [{ path: "/home", query: { size: "10" }, components: MyPage }];
const router = createRouter({
history: createWebHistory(),
routes,
});
我認為它正在用一些引數實體化路線。查看 vue devtools 的 Routing 部分會顯示一個空查詢物件:
$route:/home
fullPath:"/home"
path:"/home
query:Object (empty)
hash:""
name:undefined
params:Object (empty)
matched:Array[0]
meta:Object (empty)
redirectedFrom:undefined
href:"/home
如何為我的路線設定默認查詢引數?
uj5u.com熱心網友回復:
這是使用beforeEachNavigationGuard 的建議:
const routes = [{ path: "/home", name: "Home", components: MyPage }];
const router = createRouter({
history: createWebHistory(),
routes,
});
router.beforeEach((to, from) => {
if(to.name === "Home" && !to.query.hasOwnProperty("size")){
to.query.size = "10"
}
})
size這個想法是在路由不存在時添加一個默認查詢引數。
uj5u.com熱心網友回復:
在不定義每個默認值的情況下正確實作這一點的唯一方法router.push()可能是使用Navigation Gurads。您可以使用它們來獲取當前在 url 中的查詢引數,添加您需要的默認查詢引數,然后回傳新路由。
雖然我不會這樣做,但這可能是實作這一目標的最簡單方法。
如果您想通過pinia / vuex使它們可定制,您需要設定一個商店并進行用戶輸入以更改設定。
注意:Pania 很可能是更好的選擇,因為它更新并且在未來很長一段時間內仍會受到支持
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/465373.html
