From bfa69a312397a6df2ee5bedf4ac25ebcec84cf24 Mon Sep 17 00:00:00 2001 From: shanyun Date: Tue, 18 Oct 2022 22:21:38 +0800 Subject: [PATCH] =?UTF-8?q?=E7=AC=AC=E4=B9=9D=E5=91=A8=E4=BD=9C=E4=B8=9A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- router.js | 58 +++++++++++++++++++++++++++++++++++++++------- test/index.spec.js | 2 ++ 2 files changed, 52 insertions(+), 8 deletions(-) diff --git a/router.js b/router.js index d8926ea..6ef5766 100644 --- a/router.js +++ b/router.js @@ -1,32 +1,74 @@ function Router(routes, defaultRoute) { - //TODO + this.routes = routes + this.init(routes, defaultRoute) + this.history = [] + this.index = -1 + if (this.currentRoute) { + this.history.push(this.currentRoute.id) + this.index++ + } } //初始化,可多次初始化 Router.prototype.init = function(routes, defaultRoute) { - //TODO - this.currentRoute - this.oldRoute + this.currentRoute = routes.reduce((acc, curr) => { + if (!acc && curr.id === defaultRoute) { + return curr + } + return acc + }, null) || '' + this.oldRoute = '' } //切换路由 Router.prototype.push = function(route, callback) { - //TODO + tempOldCurr = this.currentRoute || '' + this.changeRoute(route) + if (this.currentRoute !== tempOldCurr) { + this.history.push(this.currentRoute.id) + this.index++ + if ((this.history.length > this.index - 1) && (this.index - 1 > -1)) { + this.oldRoute = this.history[this.index - 1] + } + } + return callback && callback() } //前进 Router.prototype.forward = function () { - history.forward(); + // history.forward(); + this.index++ + if ((this.history.length > this.index) && (this.index > -1)) { + this.changeRoute(this.history[this.index]) + } } //后退 Router.prototype.back = function () { - history.back(); + // history.back(); + this.index-- + if ((this.history.length > this.index) && (this.index > -1)) { + this.changeRoute(this.history[this.index]) + } +} + +Router.prototype.replace = function(route) { + this.changeRoute(route) + this.history[this.index] = this.currentRoute +} + +Router.prototype.changeRoute = function(route) { + this.currentRoute = this.routes.reduce((acc, curr) => { + if (!acc && curr.id === route) { + return curr + } + return acc + }, null) || this.currentRoute } //切换页面:route为字符串,为空则隐藏所有路由 Router.prototype.changePage = function(route) { - //TODO + // TODO } module.exports = Router \ No newline at end of file diff --git a/test/index.spec.js b/test/index.spec.js index 27b7c39..05eda9f 100644 --- a/test/index.spec.js +++ b/test/index.spec.js @@ -1,3 +1,5 @@ +// import { Router } from '../router' +const Router = require('../router.js') describe('初始化路由', () => { it('default route', () => { //路由表