路由模式
vue2安装使用的是vue-router@3
vue3安装使用的是vue-router@4
vue-router@3和vuerouter@4的区别
- vue-router@3
通过
mode设置路由模式const router = new VueRouter({ routes: [], mode: 'history | hash | abstact' }) - vue-router@4
通过
history设置路由模式const router = createRouter({ routes: [], history: createWebHistory() | createWebHashHistory() | createWebMemoryHistory() })
路由模式的区别
-
hash模式
hash跳转页面是通过
window.location.hash(path)方式实现的。hash 模式 下,url地址栏会以
#开头,hash是URL中hash(#)及后面的部分,常用作锚点在页面内进行导航。改变URL中的hash部分不会引起页面刷新。
通过
hashchange事件监听URL的变化,改变URL的方式只有这几种:- 通过浏览器前进后退改变URL
- 通过
<a>标签改变URL - 通过window.location改变URL
-
history模式
基于h5的
history去实现的history提供了
pushState和replaceState两个方法,这两个方法改变 URL 的path部分不会引起页面刷新history提供了类似hashchange事件的popstate事件,但popstate事件有些不同:
- 通过浏览器前进后退改变URL时会触发opstate事件
- 通过pushState/replaceState或
<a>标签改变URL不会触发popstate事件 - 但是我们可以拦截psuhState/replaceState的调用和
<a>标签的点击事件来监测URL变化 - 通过js的history的back、go、forward方法会触发popstate事件 所以监听URL变化可以实现,只是没有hashchange方便