hash路由
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button id="myBtn">改变</button>
</body>
<script>
const myBtn = document.getElementById("myBtn")
window.addEventListener('DOMContentLoaded', () => {
console.log(location.hash)
})
myBtn.addEventListener('click', () => {
location.href = '#/user'
})
window.onhashchange = e => {
console.log('旧url: ', e.oldURL)
console.log('新url: ', e.newURL)
console.log('hash: ', location.hash)
}
</script>
</html>
history路由
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button id="myBtn">改变url</button>
</body>
<script>
const myBtn = document.getElementById("myBtn")
window.addEventListener('DOMContentLoaded', () => {
console.log('path: ', location.pathname)
})
myBtn.addEventListener('click', () => {
const state = {name: 'user'}
history.pushState(state, '', 'user')
console.log('切换路由到了: ', 'user')
})
window.onpopstate = e => {
console.log('onpopstate', e.state, location.pathname)
}
</script>
</html>