模式
一、hash
hash模式是vue-router的默认模式。hash改变的是url锚点,当改变锚点时,浏览器只会修改访问的历史数据,不会访问服务器重新获取页面。
url形式
https://cxjdhd.jse.edu.cn/#/index
实现原理
- 通过
location.hash = '/haspath'的方式修改hash值 - 监听锚点的变化
window.addEventListener('haschange', () => {
const hash = window.location.hash.substr(1)
})
二、history
url形式
https://cxjdhd.jse.edu.cn/index
实现原理
- 改变url history提供pushState和replaceState的方法,会使url发生变化
history.pushState({},"",'/a')
- 监听url的变化
window.addEventListener("popstate", () => {
const path = window.location.pathname
// 根据path不同可渲染不同的dom
})
手写vue-router
class HistoryRoute{
constructor(){
this.current = null
}
}
class VueRouter{
constructor(options){
this.mode = options.mode || 'hash'
this.routes = options.routes || []
this.history = new HistoryRoute
this.init()
}
init(){
if(this.mode == 'hash'){
location.hash ? '' : location.hash = '/'
// 页面加载完成获取当前路由
window.addEventListener('load', () => {
this.history.current = location.hash.slice(1)
})
window.addEventListener('hashchange', () => {
this.history.current = location.hash.slice(1)
})
}else{
window.addEventListener('load', () => {
this.history.current = location.pathname
})
window.addEventListener('popState', () => {
this.history.current = location.pathname
})
}
}
}
export default VueRouter