vue-router原理
Posted 冰雪奇缘lb
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了vue-router原理相关的知识,希望对你有一定的参考价值。
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>
以上是关于vue-router原理的主要内容,如果未能解决你的问题,请参考以下文章