前端路由的实现有两种方式,一种是hash,另一种是history,至于什么是前端路由,以及这两种有什么区别网上的资料实在是太多了,但也都没有深入的讲,后续我们再来探讨;
这里就hash实现贴一个简单demo来说明,以供参考
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://unpkg.com/vue@2.6.12/dist/vue.js"></script>
<title>Hash路由</title>
</head>
<body>
<div id="app">
<div>
<a href="#index">index</a>
<a href="#com1">com1</a>
<a href="#com2">com2</a>
<a href="#com3">com3</a>
</div>
<h1>
<component :is="comName"></component>
</h1>
</div>
<script>
let vue = new Vue({
el: '#app',
data: {
comName: 'index'
},
components: {
index: {
template: '<div>index</div>'
},
com1: {
template: '<div>com1</div>'
},
com2: {
template: '<div>com2</div>'
},
com3: {
template: '<div>com3</div>'
}
}
})
window.onhashchange = function (event) {
let hash = location.hash.slice(1);
switch (hash) {
case 'com1': vue.comName = 'com1'; break;
case 'com2': vue.comName = 'com2'; break;
case 'com3': vue.comName = 'com3'; break;
default: vue.comName = 'index'; break;
}
}
</script>
</body>
</html>