js 实现路由功能
Posted honghong
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了js 实现路由功能相关的知识,希望对你有一定的参考价值。
class Router {
constructor() {
this.routes = []
}
handle(pattern, handler) {
this.routes.push({ pattern, handler })
}
exec(pathname) {
for (const route of this.routes) {
if (typeof route.pattern === ‘string‘) {
if (route.pattern === pathname) {
return route.handler()
}
} else if (route.pattern instanceof RegExp) {
const result = pathname.match(route.pattern)
if (result !== null) {
const params = result.slice(1).map(decodeURIComponent)
return route.handler(...params)
}
}
}
}
}
const router = new Router()
router.handle(‘/‘, homePage)
router.handle(/^/users/([^/]+)$/, userPage)
router.handle(/^//, notFoundPage)
function homePage() {
return ‘home page‘
}
function userPage(username) {
return `${username}‘s page`
}
function notFoundPage() {
return ‘not found page‘
}
console.log(router.exec(‘/‘)) // home page
console.log(router.exec(‘/users/john‘)) // john‘s page
console.log(router.exec(‘/foo‘)) // not found page
以上是关于js 实现路由功能的主要内容,如果未能解决你的问题,请参考以下文章