路由
路由(Router),就是对应关系
SPA与前端路由
SPA 指的是一个 web 网站只有唯一的一个 HTML 页面,所有组件的展示与切换都在这唯一一个页面内完成
此时,不同组件之间的切换需要通过前端路由来实现
前端路由
Hash 地址(# 锚链接)与组件之间的对应关系
Hash地址
如下案例展示,在点击 <a> 链接是,虽然页面不会刷新,但是 url 地址会增添 #bx 的锚链接,并且会留下浏览记录,可以在浏览器进行回退和前进
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
.box {
height: 800px;
}
#b1 {
background-color: pink;
}
#b2 {
background-color: red;
}
#b3 {
background-color: orange;
}
#b4 {
background-color: skyblue;
}
.side-bar {
position: fixed;
top: 0;
right: 0;
background-color: white;
}
</style>
</head>
<body>
<div class="side-bar">
<a href="#b1">b1</a>
<a href="#b2">b2</a>
<a href="#b3">b3</a>
<a href="#b4">b4</a>
</div>
<div class="box" id="b1"></div>
<div class="box" id="b2"></div>
<div class="box" id="b3"></div>
<div class="box" id="b4"></div>
</body>
</html>
前端路由的工作方式
- 用户点击了页面上的路由链接
- 导致了 URL 地址栏中的 Hash 值发生了变化
- 前端路由监听到了 Hash 地址的变化
- 前端路由把当前 Hash 地址对应的组件渲染到浏览器中
实现简易的前端路由
步骤1: 通过 <component> 标签,结合 comName 动态渲染组件,示例代码如下:
<!-- 通过 is 属性 指定要展示的组件的名称 -->
<component :is="comName"></component>
export default {
name: 'App',
data() {
return {
// 要展示的组件的名称
comName: 'Home'
}
}
}
步骤2: 在 APP.vue 组件中,为 <a> 链接添加对应的 hash 值:
<a href="#/home">首页</a>
<a href="#/movie">电影</a>
<a href="#/about">关于</a>
步骤3: 在 created 生命周期中,通过监听 window.onhashchange 事件监听 hash 值的变化,并且修改 comName 的值,实现不同组件的切换显示
<component :is="comName"></component>
created() {
// 只要当前的 app 组件一被创建 就立即监听 window 对象的 onhashchange 事件
window.onhashchange = () => {
console.log('监听到了 hash 地址的变化', location.hash);
switch(location.hash) {
case '#/home':
this.comName = 'Home'
break
case '#/movie':
this.comName = 'Movie'
break
case '#/about':
this.comName = 'About'
break
}
}
}