vue-router的粗浅学习
前言(胡言乱语)
作为一个辣鸡前端开发(我说我自己呢),还是用vue技术栈的,不学一学路由知识,开发的时候页面飞到哪儿去了你都不知道。
vue-router的三种模式
- history模式(HTML5History)
- hash模式(HashHistory)
- abstract模式(AbstractHistory)
1、history模式
利用支持h5 history属性的浏览器特性,它表示当前窗口的历史。
属性
History.length // 当前窗口访问过页面的数量
History.state // 当前窗口历史的栈顶数据
方法
History·back() // 后退一页
History.forward() //前进一页
HIstory.go(n: number) //前进(N>0)后退(n<0)n步
History.pushState(state, title, url) //历史记录中添加一条记录
History.replaceState(state, title, url) // 替换当前记录
state:一个与添加的记录相关联的状态对象,主要用于popstate事件。该事件触发时,该对象会传入回调函数。也就是说,浏览器会将这个对象序列化以后保留在本地,重新载入这个页面的时候,可以拿到这个对象。如果不需要这个对象,此处可以填null。
title:新页面的标题。但是,现在所有浏览器都忽视这个参数,所以这里可以填空字符串。
url:新的网址,必须与当前页面处在同一个域。浏览器的地址栏将显示这个网址。
事件
History.popstate()
每当同一个文档的浏览历史(即history对象)出现变化时,就会触发popstate事件。
注意,仅仅调用pushState()方法或replaceState()方法 ,并不会触发该事件,只有用户点击浏览器倒退按钮和前进按钮,或者使用 JavaScript 调用History.back()、History.forward()、History.go()方法时才会触发。另外,该事件只针对同一个文档,如果浏览历史的切换,导致加载不同的文档,该事件也不会触发。
使用的时候,可以为popstate事件指定回调函数。
window.onpopstate = function(event) {
console.log('location: ' + document.location);
console.log('state: ' + JSON.stringify(event.state));
}
// 或者
window.addEventListener("popstate", function() {
console.log('location: ' + document.location);
console.log('state: ' + JSON.stringify(event.state));
})
回调函数的参数是一个event事件对象,它的state属性指向pushState和replaceState方法为当前 URL 所提供的状态对象(即这两个方法的第一个参数)。上面代码中的event.state,就是通过pushState和replaceState方法,为当前 URL 绑定的state对象。
var currentState = history.state;
2、hash模式
原理是onhashchange事件,url都会被浏览器记录下来,只能改变#后面的url片段
window.onhashchange = function(event){
console.log(event.oldURL, event.newURL);
let hash = location.hash.slice(1);
document.body.style.color = hash;
}