Files
read_book/src/renderer/src/hooks/useRouterHook.ts
2026-01-08 00:12:19 +08:00

85 lines
2.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { type LocationQueryRaw, type RouteParamsRaw, useRoute, useRouter } from 'vue-router'
import { warn } from 'vue'
export function useRouterHook() {
const router = useRouter()
const route = useRoute()
const go = (to: string, query?: LocationQueryRaw, params?: RouteParamsRaw) => {
if (!to) return warn('useRouterHook: 路由路径不能为空')
// 如果有 params通常意味着你在尝试匹配动态路由
// 在 Vue Router 4 中,这种情况下必须配合 name 使用,或者手动拼接到 path 字符串中
if (params && Object.keys(params).length > 0) {
// 方案 1强制使用 name 跳转 (前提是你的 to 传入的是路由名字)
router
.push({
name: to,
query,
params
})
.catch((err) => console.error(err))
} else {
// 方案 2普通的路径跳转
router
.push({
path: to,
query
})
.catch((err) => console.error(err))
}
}
const replace = (to: string, query?: LocationQueryRaw, params?: RouteParamsRaw) => {
if (!to) return warn('useRouterHook: 路由路径不能为空')
if (route.path === to) return warn('useRouterHook: 路径不能与当前路径相同')
// 如果有 params通常意味着你在尝试匹配动态路由
// 在 Vue Router 4 中,这种情况下必须配合 name 使用,或者手动拼接到 path 字符串中
if (params && Object.keys(params).length > 0) {
// 方案 1强制使用 name 跳转 (前提是你的 to 传入的是路由名字)
router
.replace({
name: to as string,
query,
params
})
.catch((err) => console.error(err))
} else {
// 方案 2普通的路径跳转
router
.replace({
path: to as string,
query
})
.catch((err) => console.error(err))
}
}
// --- 其他方法保持不变 ---
const goBack = (n: number = 1) => {
if (window.history.length <= 1) return warn('useRouterHook: 无可返回记录')
router.go(-n)
}
const getQuery = (key?: string) => {
return key ? (route.query[key] as string | undefined) : { ...route.query }
}
const getParams = (key?: string) => {
return key ? (route.params[key] as string | undefined) : { ...route.params }
}
return {
router,
route,
go,
replace,
goBack,
getQuery,
getParams,
refresh: () => router.go(0)
}
}
export default useRouterHook