Table of contents
1. The routing mode of vue-router
3. How to choose between the two
1. The routing mode of vue-router
- hash
- H5 history (need to configure mode:history, need back-end cooperation)
1.1 hash routing
1.1.1 Features of hash
- Hash changes will trigger webpage jumps, that is, the forward and backward of the browser
- Hash changes will not refresh the page, a necessary feature for SPA
- The hash will never be submitted to the server side (the front end lives on its own)
1.1.2 Code Demonstration
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>hash test</title>
</head>
<body>
<p>hash test</p>
<button id="btn1">修改 hash</button>
<script>
// hash 变化,包括:
// a. JS 修改 url
// b. 手动修改 url 的 hash
// c. 浏览器前进、后退
window.onhashchange = (event) => {
console.log('old url', event.oldURL)
console.log('new url', event.newURL)
console.log('hash:', location.hash)
}
// 页面初次加载,获取 hash
document.addEventListener('DOMContentLoaded', () => {
console.log('hash:', location.hash)
})
// JS 修改 url
document.getElementById('btn1').addEventListener('click', () => {
location.href = '#/user'
})
</script>
</body>
</html>
1.2 H5 history routing
1.2.1 Features of H5 history
- Route with url specification, but do not refresh the page when jumping
- history.pushState
- window.onpopstate
1.2.2 Code Demonstration
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>history API test</title>
</head>
<body>
<p>history API test</p>
<button id="btn1">修改 url</button>
<script>
// 页面初次加载,获取 path
document.addEventListener('DOMContentLoaded', () => {
console.log('load', location.pathname)
})
// 打开一个新的路由
// 【注意】用 pushState 方式,浏览器不会刷新页面
document.getElementById('btn1').addEventListener('click', () => {
const state = { name: 'page1' }
console.log('切换路由到', 'page1')
history.pushState(state, '', 'page1') // 重要!!
})
// 监听浏览器前进、后退
window.onpopstate = (event) => { // 重要!!
console.log('onpopstate', event.state, location.pathname)
}
// 需要 server 端配合,可参考
// https://router.vuejs.org/zh/guide/essentials/history-mode.html#%E5%90%8E%E7%AB%AF%E9%85%8D%E7%BD%AE%E4%BE%8B%E5%AD%90
</script>
</body>
</html>
2. Summary
- hash - window.onhashchange
- H5 history - history.pushState 和 window.onpopstate
- H5 history requires backend support
3. How to choose between the two
- The system of to B recommends using hash, which is easy to use and not sensitive to url rules
- To C system, you can consider choosing H5 history (SEO, performance optimization), but server-side support is required
- If you can choose simple ones, don’t use complicated ones, and consider costs and benefits