利用HTML5的history和hash修改当前页面的URL
history
<div id="box">用history改变url值</div>
<script>
let oBox = document.getElementById('box')
// 页面路径
window.addEventListener('DOMContentLoaded', () => {
console.log(location.pathname);
})
oBox.addEventListener('click', () => {
let routPath = { name: "/login", query: { user: "dsadsad" } }
history.pushState(routPath, "dsadsad", 'login')
})
// 监听浏览器前进后退
window.onpopstate = (e) => {
console.log(location.pathname);
}
hash
<div id="box">hash的值</div>
<script>
let oBox = document.getElementById('box')
window.onhashchange = (e) => {
console.log('e.oldURL', e.oldURL);
console.log('e.oldURL', e.newURL);
console.log('location.hash', location.hash);
}
window.addEventListener('DOMContentLoaded', () => {
console.log('location.pathname', location.pathname);
})
oBox.addEventListener('click', () => {
location.href = '#/user'
})