Hash 模式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<nav class="nav-box">
<a href="#/">首页</a>
<a href="#/about">关于</a>
<a href="#/product">产品</a>
</nav>
<div id="app"></div>
<script>
const app = document.querySelector('#app')
const navBox = document.querySelector('.nav-box')
const routes = [
{
path: '/',
component: '组件-首页home'
},
{
path: '/about',
component: '组件-关于我们'
},
{
path: '/product',
component: '组件-产品列表'
}
]
const routeMatch = () => {
const hash = location.hash.substring(1)
let text = ''
routes.forEach(it => {
if(it.path === hash) text = it.component
})
app.innerHTML = text
}
location.hash = '/'
routeMatch()
window.onhashchange = routeMatch
</script>
</body>
</html>
H5的history模式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<nav class="nav-box">
<a href="/">首页</a>
<a href="/about">关于</a>
<a href="/product">产品</a>
</nav>
<div id="app"></div>
<script>
const app = document.querySelector('#app')
const navBox = document.querySelector('.nav-box')
const routes = [
{
path: '/',
component: '组件-首页home'
},
{
path: '/about',
component: '组件-关于我们'
},
{
path: '/product',
component: '组件-产品列表'
}
]
navBox.onclick = (event) => {
if(event.target.tagName === 'A') {
event.preventDefault()
history.pushState({}, '', event.target.href)
routeMatch()
}
}
const routeMatch = () => {
const pathname = location.pathname
let text = ''
routes.forEach(it => {
if(it.path === pathname) text = it.component
})
app.innerHTML = text
}
history.pushState(null, '', '/')
routeMatch()
window.onpopstate = routeMatch
</script>
</body>
</html>