前端路由实现方式
HistoryApi
window.history.length
window.history.state
window.history.go([delta])
window.history.back()
window.history.forward()
window.history.pushState(data,title,url)
window.history.replaceState(data,title,url)
我们只看最后两个API
/**
*parameters
*@data {object} state对象,这是一个javascript对象,一般是JSON格式的对象
*字面量。
*@title {string} 可以理解为document.title,在这里是作为新页面传入参数的。
*@url {string} 增加或改变的记录,对应的url,可以是相对路径或者绝对路径,
*url的具体格式可以自定。
*/
history.pushState(data,title,url) //向浏览器历史栈中增加一条记录
history.replaceState(data,title,url) //替换历史栈中的当前记录
复制代码
这两个Api都会操作浏览器的历史栈,而不会引起页面的刷新。不同的是,pushState会增加一条新的历史记录,而replaceState则会替换当前的历史记录。所需的参数相同,在将新的历史记录存入栈后,会把传入的data(即state对象)同时存入,以便以后调用。同时,这俩api都会更新或者覆盖当前浏览器的title和url为对应传入的参数。
url参数可以为绝对路径:www.tonylee.pw/name/tonyle…
也可以为相对路径:?name=tonylee , /name/tonylee
//假设当前网页URL为:http://tonylee.pw
window.history.pushState(null, null, "http://tonylee.pw?name=tonylee");
//url变化:http://tonylee.pw -> http://tonylee.pw?name=tonylee
window.history.pushState(null, null, "http://tonylee.pw/name/tonylee");
//url变化:http://tonylee.pw -> http://tonylee.pw/name/tonylee
window.history.pushState(null, null, "?name=tonylee");
//url变化:http://tonylee.pw -> http://tonylee.pw?name=tonylee
window.history.pushState(null, null, "name=tonylee");
//url变化:http://tonylee.pw -> http://tonylee.pw/name=tonylee
window.history.pushState(null, null, "/name/tonylee");
//url变化:http://tonylee.pw -> http://tonylee.pw/name/tonylee
window.history.pushState(null, null, "name/tonylee");
//url变化:http://tonylee.pw -> http://tonylee.pw/name/tonylee
//错误的用法:
window.history.pushState(null, null, "http://www.tonylee.pw?name=tonylee");
//error: 由于跨域将产生错误
可以看到,url作为一个改变当前浏览器地址的参数,用法是很灵活的,replaceState和pushState具有和上边测试相同的特性,传入的url如果可能,总会被做适当的处理,这种处理默以”/”相隔,也可以自己指定为”?”等。要注意,这两个api都是不能跨域的
复制代码
Url作为一个改变当前浏览器地址的参数,会被做适当的处理,这种处理默以”/”相隔,也可以自己指定为”?”等。要注意,这两个api都是不能跨域的
popstate
当同一个页面在历史记录间切换时,就会产生popstate事件。正常情况下,如果用户点击后退按钮或者开发者调用:history.back() or history.go(),页面根本就没有处理事件的机会,因为这些操作会使得页面reload。所以popstate只在不会让浏览器页面刷新的历史记录之间切换才能触发,这些历史记录一般由pushState/replaceState或者是由hash锚点等操作产生。并且在事件的句柄中可以访问state对象的引用副本!而且单纯的调用pushState/replaceState并不会触发popstate事件。
Hashchange
当页面hash(#)变化时,即会触发hashchange。锚点Hash起到引导浏览器将这次记录推入历史记录栈顶的作用, window.location 对象处理“#”的改变并不会重新加载页面,而是将之当成新页面,放入历史栈里。
hash+hashchange 实现
location.hash始终指向页面url 中#之后的内容
当当前页面的url ='www.baidu.com',可以在浏览器的控制台输入location.hash为空,当页面指向url ='www.baidu.com/#/hello'的时候,location.hash = '#/hello'。通过读取location.hash可以知道当前页面所处的位置。通过hashchange事件可以监听location.hash的变化,从而进行相应的处理即可。
那么如何触发hash的改变呢?这里主要由两种方法:
1.设置a标签,href = '#/blue',当点击标签的时候,可以在当前url的后面增加上'#/blue',同时触发hashchange,再回调函数中进行处理。
2.直接在js中对location.hash = '#/blue'即可,此时url会改变,也会触发hashchange事件。
仅用于个人整理,参考: