解释
history对象包含用户在浏览器窗口中访问过的 URL——是 window 对象的一部分,可通过 window.history 属性对其进行访问。
它是路由的基石,不论是Vue、react、angular等框架,其都离不开根本的路由,了解路由的基石还是很有必要的。
方法
方法 | 描述 |
---|---|
push(path) | 往history中添加路由 |
replace(path) | 替换history中的路由 |
back() | 加载 history 列表中的前一个 URL |
goForward() | 加载 history 列表中的下一个 URL |
listen() | 监听 history 列表中记录的变化 |
go() | 加载 history 列表中的某个具体页面 |
history采用栈的后进先出的模式记录存储路由、锚点的信息,比如我创建historyObj.html页面,该页面首先入栈。以下historyObj.html代页面码。
源代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>深入理解history对象</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<a href="https://www.baidu.com" onclick="return push('/test1')">push test1</a><br><br>
<button class="btn btn-default" onclick="push('/test2')">push test2</button>
<br><br>
<button class="btn btn-default" onclick="replace('/test3')">replace test2</button>
<br><br>
<button class="btn btn-default" onclick="back()"><=回退</button>
<br><br>
<button class="btn btn-default" onclick="forword()">前进=></button>
<br><br>
<button class="btn btn-default" onclick="go(2)">跳转</button>
<script type="text/javascript" src="https://cdn.bootcss.com/history/4.7.2/history.js"></script>
<script>
//方法1,直接使用h5推出的history身上的API
let history = History.createBrowserHistory();
//hash值(锚点)
// let history = History.createHashHistory()
//往history中添加路由
const push = (path) => {
history.push(path)
return false
}
//监听历史记录的变化
history.listen((location) => console.log("请求路由path变化了", location))
</script>
</body>
</html>
push函数
back函数
实现页面中后退按钮,在script
标签中增加如下代码:
//历史记录回退
const back =() => {
history.goBack();
}
- 单击
push test1
按钮 - 单机
push test2
按钮 - 单机
回退按钮
- 再次单机
回退
按钮
forward函数
实现页面中前进按钮,在script
标签中增加如下代码:
//前进
const forward = () =>{
history.goForward();
}
- 单击
push test1
按钮 - 单机
push test2
按钮, - 单机
回退
按钮 - 再次单机
回退
按钮 - 单机
前进
按钮 - 再次单机
前进
按钮
可以看到监听结果:
当单机前进按钮时,可以看到/test1
和/test2
依次入栈
replace函数
replace函数可以替换某个路由,比如我们后台登陆之后,一般不能再次回退到登录页面,我们可以使用这个函数。
//替换某个路由
const replace = (path) => {
history.replace(path)
}
- 单击
push test1
按钮 - 单机
push test2
按钮 - 单机
replace test2
按钮 - 单机
回退
按钮 - 单机
前进
按钮时,本来应该跳转/test2
路由,但/test2
被/test3
替换了,因而,直接跳转到//test3
,如图所示:
画出如下栈内存:
go函数
go兼具back函数和forward的函数,当go的实参大于0时,具有前进跳转的功能,如果小于0,则表示后退。
//go跳转
const go = (num) => {
console.log("num=",num)
history.go(num)
}
- 单击
push test1
按钮 - 单机
push test2
按钮 - 单机
回退
按钮 - 再次单机
回退
按钮,路由回到了主页面中 - 单机
跳转
按钮,因为跳转按钮写的是2,直接跳转到/test2
路由,如图所示:
如果我们将2修改为-2,则会回退到主页面/historyObj.html
,如图所示:
createHashHistory
我们取消源代码中的let history = History.createHashHistory()
的注释,注释let history = History.createBrowserHistory();
,再次执行上诉代码,可以清晰的看到:
当我单机 push test2
按钮时,会发现路由地址是这样的:http://localhost:63342/bloghtml/historyObj.html#/test2
,但createBrowserHistory的路由是这样的:http://localhost:63342/test2
因为createHashHistory是采用锚点的形式,createBrowserHistory()是路由的形式。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/99205.html