Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

第九周作业 #7

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 50 additions & 8 deletions router.js
Original file line number Diff line number Diff line change
@@ -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
2 changes: 2 additions & 0 deletions test/index.spec.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// import { Router } from '../router'
const Router = require('../router.js')
describe('初始化路由', () => {
it('default route', () => {
//路由表
Expand Down