关键字:location、history、hashchange、popstate、hash、history
location和history
window.location
window.location 对象可用于获取当前页面地址(URL)并把浏览器重定向到新页面。
-
主要属性
- hash 设置或返回从井号 (#) 开始的 URL(锚)。
- host 设置或返回主机名和当前 URL 的端口号。
- hostname 设置或返回当前 URL 的主机名。
- href 设置或返回完整的 URL。
- pathname 设置或返回当前 URL 的路径部分。
- port 设置或返回当前 URL 的端口号。
- protocol 设置或返回当前 URL 的协议。
- search 设置或返回从问号 (?) 开始的 URL(查询部分)。
-
举个例子
在浏览器输入如下URL:
https://www.baidu.com/aaa?bbb=ccc#ddd
在控制台获取到的location信息如下:
window.history
History 对象包含用户(在浏览器窗口中)访问过的 URL。
- 主要方法
- back() 加载 history 列表中的前一个 URL。
- forward() 加载 history 列表中的下一个 URL。
- go() 加载 history 列表中的某个具体页面。
- pushState() 把一个url添加到history列表,用法:pushState(state, title, url)
- replaceState() 把当前url替换成新的url,用法:replaceState(state, title, url)
location和history区别
一句话总结:location包含当前url的信息;history包含当前站点前后url变化的信息。
hashchange和popstate
hashchange事件是在浏览器URL中hash发生变化(location.hash)后触发的事件,URL中#后的内容就是hash
popstate事件是在用户点击浏览器的前进后退按钮(history中的back\forward\go)时, 就会触发popState事件。特别需要注意的pushState和replaceState这两个方法只会改变history列表信息,不会触发popState事件。
hash模式和history模式
vue-router(前端路由)有两种模式,分别是hash模式和history模式。而这两种模式的实现原理正是监听了hashchange和popstate两个事件。