路由的模式
路由分为hash模式和history模式,这两个模式最显著的区别就是hash模式url带#号,history模式不带#号。
hash模式原理
这个模式主要通过监听hash值的变化,更改页面的内用,用原生js给大家演示一下
- 我们创建两个a元素,分别跳转到home页面,和about页面
- 创建一个div用来展示两个页面的内容,结构如下
<a href="#/about">about</a>
<a href="#/home">home</a>
<div class="counter"></div>
hash模式href要带#的
- 首先我们监听hash值得变化,用hashchange事件
- 当hash值变化后,我们判断此时的hash值是什么,由此来展示特定的页面
- 可以用location.hash获取此时的hash值
let counterEl = document.querySelector(".counter") //获取div用来展示内容
window.addEventListener("hashchange",()=>{ //监听hashchange事件
switch(location.hash){
case "#/home": //判断hash
counterEl.innerHTML = "home"
break;
case "#/about":
counterEl.innerHTML = "about"
break;
}
})
这样,一个简单的路由就完成了,我们来看一下效果怎么样
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-FFZyMLi9-1655552875553)(https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/716c82e8e9994b92989c6d575e3571ec~tplv-k3u1fbpfcp-zoom-in-crop-mark:1956:0:0:0.image?)]
没有问题
history模式
history模式提供了好几种Api
- pushState,会在浏览器留下记录,可以通过返回按钮返回
- replaceState,不会在浏览器留下记录,无法返回
- go(n),前进n,但是必须后退过,才能用
- forward, 前进1
- break, 后退1
我自己的理解就是pushState是有浏览记录的,而replaceState属于无痕浏览
pushState接收三个参数,我们主要说的是第三个,他会转到第三个参数对应的页面
history实现路由
history模式通过监听a元素的点击事件,判断此时的location.pathName来跳转路由
- 首先监听a的点击事件
- 清除a的副作用
- 根据a元素的href改变浏览器url,用history.pushState()
- 获取location.pathName
- 根据location.pathName显示页面被容
HTML
<a href="/about">about</a>
<a href="/home">home</a>
<div class="counter"></div>
JS
const counter = document.querySelector(".counter")
const aEls = document.getElementsByTagName("a")
for (const aEl of aEls) {
aEl.addEventListener("click",(e)=>{
e.preventDefault() //清除a的副作用
const href = aEl.getAttribute("href") //此时拿到的是a元素的href
history.pushState({},"",href) //通过history.pushState跳转
switch(location.pathname){ //判断此时的pathName,决定界面显示内容
case "/about":
counter.innerHTML = "about"
break;
case "/home":
counter.innerHTML = "home"
break;
}
})
}
这样一个简易history路由就完成了
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-yWpGM9f2-1655552875553)(https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/836519aeca214f43b663cf0f9be11b80~tplv-k3u1fbpfcp-zoom-in-crop-mark:1956:0:0:0.image?)] go,forward这些Api很简单,就不给大家演示
结束
祝大家幸福!