简单实现前端路由
Talk is cheap, show me the code
路由的概念来源于服务端,而在Web前端的SPA应用中,路由主要用于建立URL和UI的映射关系,即URL 变化引起 UI 更新,无需刷新页面。
前端路由
前端路由主要解决两个问题:
- URL改变不引起页面刷新
- 检测URL变化
常用方法有两种: hash mode和history mode
hash mode
hash的来源是锚点,在页面内进行内部导航和跳转用的,也就是#后面的部分
通过hashchange可以监听URL的变化。
改变URL的方式只有以下几种:
- 浏览器前进后退
- 通过a标签改变
- 通过window.location改变
这几种改变会触发hashchange
history mode
history提供pushState和replaceState方法,这两个方法改变path部分不引起页面刷新
history也有类似hashchange事件就是popstate事件。
不同的地方是,通过浏览器前进后退会触发popstate
通常通过pushState/replaceState和a标签改变URL是不会触发popstate的
但是可以通过拦截pushState/replaceState和a标签的调用来检测URL变化。
原生实践
基于hash
html部分
|
|
script部分
|
|
基于history
html部分一样
|
|
Vue Router
基于hash
router-link 组件
|
|
router-view 组件
|
|
main.js入口
|
|
基于history
router-link 组件
router-view组件
|
|
main.js入口文件一样