diff --git a/index.html b/index.html index 005cf18..587e8cf 100644 --- a/index.html +++ b/index.html @@ -33,11 +33,7 @@

Welcome

title: '首页' }, { id: 'next', - title: '下一页', - handler: function() { - console.log("切换到next"); - console.log(this); - } + title: '下一页' }] //路由器 diff --git a/package.json b/package.json index 54eb422..2de877f 100644 --- a/package.json +++ b/package.json @@ -15,6 +15,7 @@ "author": "", "license": "ISC", "dependencies": { + "http-server": "^14.1.1", "jest": "^29.0.0", "jest-environment-jsdom": "^29.1.2" } diff --git a/router.js b/router.js index d8926ea..eb4a329 100644 --- a/router.js +++ b/router.js @@ -1,32 +1,62 @@ function Router(routes, defaultRoute) { //TODO + this.init(routes, defaultRoute); } //初始化,可多次初始化 -Router.prototype.init = function(routes, defaultRoute) { +Router.prototype.init = function (routes, defaultRoute) { //TODO - this.currentRoute - this.oldRoute -} + this.routes = routes; + this.routeMap = {}; + routes.forEach((currenValue) => { + this.routeMap[currenValue.id] = currenValue; + }); + this.stack = []; + this.stackIndex = -1; + this.push(defaultRoute); +}; //切换路由 -Router.prototype.push = function(route, callback) { - //TODO -} +Router.prototype.push = function (route, callback) { + this.changePage(route); + history.pushState(this.currentRoute, this.currentRoute.title); + let res; + if (callback) { + try { + res = callback(this.currentRoute, this); + } catch (error) { + res = undefined; + } + } + return res; +}; +Router.prototype.replace = function (route) { + this.changePage(route); + history.replaceState(this.currentRoute, this.currentRoute.title); +} //前进 Router.prototype.forward = function () { history.forward(); -} + this.stackIndex++; + this.currentRoute = this.stack[this.stackIndex]; +}; //后退 Router.prototype.back = function () { history.back(); -} + this.stackIndex--; + this.currentRoute = this.stack[this.stackIndex]; +}; //切换页面:route为字符串,为空则隐藏所有路由 -Router.prototype.changePage = function(route) { - //TODO -} +Router.prototype.changePage = function (route) { + // TODO + const currentRoute = this.routeMap[route]; + this.currentRoute = currentRoute; + this.stack.push(currentRoute); + this.stackIndex++; +}; + -module.exports = Router \ No newline at end of file +module.exports = Router; \ No newline at end of file diff --git a/test/index.spec.js b/test/index.spec.js index 27b7c39..7408303 100644 --- a/test/index.spec.js +++ b/test/index.spec.js @@ -1,3 +1,5 @@ +const Router = require('../router'); + describe('初始化路由', () => { it('default route', () => { //路由表