单页面应用(只有一个主页面的应用)
(一)mode(模式)
(1)hash模式(默认模式)
URL链接中的#符号(不是密码学中的散列运算)
(如URL链接为http://www.abc.com/#/hello
,hash 的值为 #/hello
)
使用URL的hash来模拟一个完整的URL,当URL改变时,页面不会重新加载。
(2)history模式
当使用history模式时,URL就要像正常的url,如http://yoursite.com/user/id,但这需要后台支持。
两种模式对比详解见文章:(https://blog.csdn.net/lyn1772671980/article/details/80804419)
(二)this.$route 和 this.$router 区别
(1)this.$route
表示当前正在用于跳转的路由对象,可以调用其name、path、query、params等方法;
console.log(this.$route.name)//登录 console.log(this.$route.path)// / console.log(this.$route.params)// {}
(2)this.$router
表示全局的路由对象,项目中通过router路由参数注入路由之后,在任何一个页面都可以通过此方法获取到路由对象,并调用其push(), go()等方法
this.$router.push('/home') // 跳转到home页 this.$router.go(-1) // 回退上一页
PS:(1)两者相差一个单词,但作用不同,切莫弄混。(2)直接打印this.$route 或 this.$router 会报 “ Property or method "toJSON" is not defined on the instance but referenced during render” 错误
(三)全局导航(全局守卫)
“导航” 表示路由正在发生变化
router.beforeEach((to,from,next)=>{})全局前置守卫
router.afterEach((to,from,next)=>{})全局后置守卫
全局导航 离开路由触发
to即将去往的路由对象
from当前导航正要离开的路由
next() 一定要调用该方法来 resolve 这个钩子(Function 必须要的 否则页面可能会空白)
next()进入管道的下一钩子
next(false)中断当前的导航
const router = new VueRouter({ ... })
router.beforeEach((to, from, next) => { store.commit('getBreadRouter',to.matched) next() })
也可以在路由配置上直接定义beforeEnter
守卫
const router = new VueRouter({ routes: [ { path: '/foo', component: Foo, beforeEnter: (to, from, next) => { // ... } } ] })