订阅API
当 URL 修改或导航事件发生时,这些 API 会通知您的 JavaScript 代码。
onPage
订阅特定的路由模式。每当匹配的状态转换(例如,从活动到非活动,或参数更改)时,回调就会触发。
typescript
function onPage(
pattern: string,
callback: (active: boolean, location: PageLocation) => void,
exact: boolean = true,
matchGroup?: string
): () => void- 返回一个清理函数以取消订阅。
active:true(如果当前位置与模式匹配)。location: 包含pathname、query(搜索参数)、data(历史状态)和解析的params的对象。
示例
javascript
import { onPage } from '@beforesemicolon/router'
const unsubscribe = onPage('/users/:userId', (active, location) => {
if (active) {
console.log(`Now viewing user: ${location.params.userId}`)
console.log('State payload:', location.data)
} else {
console.log('Navigated away from user profile')
}
})
// Later: clean up listener
// unsubscribe();使用 exact = false 订阅布局路径及其后代:
javascript
onPage(
'/docs',
(active) => {
docsShell.hidden = !active
},
false
)onPageChange
订阅所有全球位置转换。在任何导航事件后触发,无论哪些路径处于活动状态。
typescript
type PageChangeCallback = (
pathname: string,
searchParams: Record<string, string>,
pageData: Record<string, unknown>
) => void
function onPageChange(callback: PageChangeCallback): () => void- 返回一个清理函数以取消订阅。
示例
javascript
import { onPageChange } from '@beforesemicolon/router'
onPageChange((pathname, query, state) => {
// Send analytics view event
trackPageView(pathname)
})isOnPage
帮助程序验证特定路径是否与当前浏览器位置匹配。
typescript
function isOnPage(pathname: string, exact: boolean = true): booleanexact: 如果是false,且浏览器位置以指定路径开头(将子路径视为匹配),则计算结果为true。
示例
javascript
// Browser is at: /todos/123?filter=all
isOnPage('/todos') // false (not exact)
isOnPage('/todos', false) // true (subpath match)
isOnPage('/todos/123') // true (exact path match)
isOnPage('/todos/123?filter=all') // true (exact match including queries)编辑此文档[!NOTE]
isOnPage内的搜索查询匹配是顺序敏感的。参数必须按照指定的确切顺序出现。