// 定义类型
interface ISearchParams {
[key: string]: string
}
// 调用 - 获取方法
const {tabIndex} = getURLSearchParams(window.location.href)
console.log(tabIndex)
// 获取方法
function getURLSearchParams(url: string): ISearchParams {
const urlInstance = new URL(url)
const searchParamsInstance = urlInstance.searchParams
const searchParamsEntries = searchParamsInstance.entries()
const searchParams = Object.fromEntries(searchParamsEntries)
return searchParams
}
// 调用 - 更新方法
const newUrl = updateURLSearchParams(window.location.href, {
tabIndex: key
})
window.history.replaceState(null, '', newUrl)
// 更新方法
function updateURLSearchParams(
url: string,
partialSearchParams: ISearchParams,
) {
const urlInstance = new URL(url)
const searchParamsInstance = urlInstance.searchParams
Object.keys(partialSearchParams).forEach((key: string) => {
const value = partialSearchParams[key]
searchParamsInstance.set(key, value)
})
const newUrl = urlInstance.toString()
return newUrl
}
// 调用 - 删除方法
const newUrl = removeURLSearchParams(window.location.href, {
tabIndex: key
})
window.history.replaceState(null, '', newUrl)
// 删除方法
function removeURLSearchParams(url: string, keys: string[]): string {
const urlInstance = new URL(url)
const searchParamsInstance = urlInstance.searchParams
keys.forEach((key: string) => {
searchParamsInstance.delete(key)
})
const newUrl = urlInstance.toString()
return newUrl
}
【切换tabs,不刷新修改链接参数】
于 2022-09-21 15:38:51 首次发布