Vue之Router

一世执手 提交于 2019-12-02 05:39:29

单页面应用(只有一个主页面的应用)

(一)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

详情见官网链接:(https://router.vuejs.org/zh/guide/essentials/history-mode.html#%E5%90%8E%E7%AB%AF%E9%85%8D%E7%BD%AE%E4%BE%8B%E5%AD%90

 

(二)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) => {
        // ...
      }
    }
  ]
})

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!