美文网首页
vue路由使用

vue路由使用

作者: hijackli | 来源:发表于2019-07-14 00:51 被阅读0次
    • vue add router 使用历史模式吗?Y

    • 项目中生成router.js文件,所以在main.js主入口文件中引入import router from './router.js'

    • new Vue({router: router})中使用

    • routes:[]component:() => import('./views/Home.vue');懒加载

    • routes:[]redirect: () => { console.log(to.path) }重定向导航

    • routes:[]path: '*'以上所有导航不匹配时的其余路径

    • 导航选中class类名router-link-exact-active router-link-active

    • this.$router.push('/home'); js控制导航到某个位置

    • this.$route 返回当前页面导航信息参数,如paramspath

    • 动态路由:

      • <router-link :to="{name: 'question', params: {id: ...}}"></router-link>必须使用name属性,使用path属性不起作用
      • this.$router.push({ name: 'question',params: {id:...} })设置跳转路由路径,一般更新了路径页面不跳转,需要配合路由生命周期函数使用 => beforeRouteUpdate(){}路由路径更新时执行
    • 组件路由守卫

      • beforeRouteLeave(to,from,next){ next() } 路由生命周期函数,在路由离开之前执行,next执行才会切换
      • beforeRouteEnter(to,from,next) {} 路由生命周期函数,到达当前路由执行,next需要执行才能到达,并且函数内部不能获取组件实例this,如果需要获取组件实例,需要在next中获取next((vm) => { console.log(vm) })
      • beforeRouteUpdate(to,from,next){}路由路径更新时执行
    • 路由独享守卫

      • routes: [ {..., beforeEnter(to,from,next){} } ]写在router.js中某个路径下独享的守卫
    • 全局路由守卫

      • router.beforeEach((to,from,next) => { next(); })全局路由变化时守卫,main.js全局中定义
      • router.beforeResolve(to,from,next){}所有组件解析完成之前执行
      • router.afterEach(){}所有组件解析完成之后执行,没有参数
    • 路由守卫执行顺序:全局守卫beforeEach => 路由独享守卫 => 组件路由守卫 => 全局守卫beforeResolve => 全局守卫afterEach

    • 路由元信息:routes:[{..., meta:{login: true} }]

      • 通过meta来判断不太准确,因为如果使用了重定向,那么子路由就没有meta信息。但是可以通过this.$route.matched[0].meta或者导航守卫函数参数to.matched[0].meta获取
    • 通过路由元信息跳转登录

      //main.js
      router.beforeEach((to,from,next)=>{
        const needLogin = to.matched.some(item.meta && item.meta.login);
        if(needLogin) {
              const isLogin = document.cookie.includes('login=true');
              if(isLogin) {
                  next();
              }else {
                  const toLoginFlag = window.confirm('该页面需要登录才能访问,需要去登录嘛?')
                  if(toLoginFlag) {
                      next('/login');
                  }
              }
        }else {
            next();
        }
      })
      

    相关文章

      网友评论

          本文标题:vue路由使用

          本文链接:https://www.haomeiwen.com/subject/xkbvkctx.html