vue路由原理~

101 阅读1分钟

hash模式 不会刷新页面

// 监听hash的改变
window.onhashchange = (e) => {
    console.log('老url', e.oldURL);
    console.log('新url', e.newURL);
    
    console.log('hash', location.hash)
    // 重新渲染视图操作......
}
// 一进入就获取到hash
window.addEventListener('DOMContentLoaded', () => {
    console.log(location.hash)
})

// 手动改变
location.href = '#/user';

history模式 服务端需要配置无论什么页面都要返回index.html

// 一进入就获取到路径
window.addEventListener('DOMContentLoaded', () => {
    console.log('path:',location.pathname)
})

// 手动改变路径
const state = { name: 'user' }
history.pushState(state, '', 'user');
console.log('切换路由到了user')
// 监听前进后退事件
window.onpopstate = (e) => {
    console.log('onpopstate', e.state, location.pathname)
}