在讲路由hash和history模式之前,先简要说一下路由的设计理念。路由并不是某个框架特有的,它是一种设计思想。其目的是让页面的url路径改变但整个html页面不重新加载(单页面应用是局部刷新页面的),这使得我们不能使用普通的超链接方式实现路由。我们需要建立url路径和根页面中dom元素的映射关系。
简介
锚点其实就是超链接的一种,它是一种特殊的超链接,有一个#号,点击a标签后,网址url路径就会在之前的路径上加上#及#后面的内容。(我们经常使用锚点去找到页面中某元素的位置,这对于大家来说应该不陌生)。
示例代码
下面是锚点代码:
原理
通过动态锚点技术重写url路径,会在原有的url基础上加上“/#/xxx”,这种方式可以在不重新加载原有html文件的基础上,实现切换url路径的目的,然后通过onhashchange监听url路径的变化,来实现对相应dom元素的隐藏和显示,这样子看起来就像是整个页面在切换。
模拟hash模式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.container{
display: none;
}
.index{
width: 400px;
height: 400px;
background-color: #61dafb;
}
.about{
width: 400px;
height: 400px;
background-color: #61dafb;
}
</style>
</head>
<body>
<div>
<a href="#/index">首页</a>
<a href="#/about">关于</a>
<div class="container index">
首页内容
</div>
<div class="container about">
关于内容
</div>
</div>
<script>
window.onhashchange=function (event){
//截取新路径中#后面的部分
let newHash=event.newURL.split("#/")[1];
//截取旧路径中#后面的部分
let oldHash=event.oldURL.split("#/")[1];
//获取不同路径所对应页面的dom容器
let newContainer=document.querySelector('.'+newHash);
let oldContainer=document.querySelector('.'+oldHash);
//显示"新页面"容器
newContainer.style.display="block";
//隐藏"旧页面"容器
if (oldContainer){
oldContainer.style.display="none";
}
}
</script>
</body>
</html>
```
页面展示
操作过程如下,先进入页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.container{
display: none;
}
.index{
width: 400px;
height: 400px;
background-color: #61dafb;
}
.about{
width: 400px;
height: 400px;
background-color: #61dafb;
}
</style>
</head>
<body>
<div>
<a href="javascript:jump('/index')">首页</a>
<a href="javascript:jump('/about')">关于</a>
<div class="container index">
首页内容
</div>
<div class="container about">
关于内容
</div>
</div>
<script>
function jump(path){
//通过pushState重写url路径
history.pushState(null,'page',path);
//获取所有“页面”的dom元素
let containers=document.querySelectorAll(".container");
//获取当前要跳转的页面的dom元素
//下面这一行是模拟(目的是通过映射关系从path找到相应页面的dom元素)
let newContainer=document.querySelector(path.replace('/','.'));
//把所有“页面”的dom元素隐藏
containers.forEach(container=>{container.style.display="none"})
newContainer.style.display="block";
}
</script>
</body>
</html>
在项目开发阶段,很多人使用脚手架开发,会用到history模式。在页面刷新之后也没有报404,这看似与上面说的前后矛盾。但这是因为vue脚手架内部解决了history的这一问题,如果把项目部署到服务器上,这时候脱离了脚手架环境,直接刷新就会出现404问题。
因篇幅问题不能全部显示,请点此查看更多更全内容