console
const router = [
{
id: 0,
path: '/',
title: '主页',
template: '<h1>Hello</h1>'
},
{
id: 1,
path: '/blog',
title: '博客',
template: '<h1>Check it out</h1>'
},
{
id: 2,
path: '/resume',
title: '简历',
template: '<h1>My Resume</h1>'
}
]
function SueRouter(config) {
this.config = config
this.router = config.router
this.viewZone = document.querySelector(config.el)
if (!this.router)throw new Error('`config.router` can not be null.')
this.currentPage = this.router.find(r => r.path === '/') || this.router[0]
this.bindListener()
}
SueRouter.prototype.bindListener = function () {
const list = document.querySelector('#router-list')
list.addEventListener('click', (evt) => {
if (evt.target.nodeName === 'A') {
window.location.hash = evt.target.getAttribute('href')
return false
}
})
window.addEventListener("hashchange", () => {
this.routerChange()
})
}
SueRouter.prototype.render = function () {
if (this.currentPage) {
this.viewZone.innerHTML = this.currentPage.template
}
}
SueRouter.prototype.routerLinkTo = function (path) {
const page = this.router.find(r => r.path === path)
this.currentPage = page
this.render()
}
SueRouter.prototype.routerChange = function () {
console.log(change)
}
new SueRouter({
router,
el: '#view'
})
<div id="router-list">
<a href="/">主页</a>
<a href="/blog">博客</a>
<a href="/resume">简历</a>
</ul>
<div id="view">
</div>
li {
cursor:pointer;
}