Vue 路由传参,路由守卫

646 阅读1分钟

路由query传参

        App页面传参name
        <router-link to="/cldA?name=xx">CldA-1</router-link>|
        <router-link to="/cldA?name=yy">CldA-2</router-link>|
        
        
        子组件watch深度监听            
        watch:{
          $route:{
             handler:function(){
             let name=this.$route.query.name
             if(name=='xx'){
                this.msg='BBQ'
             }else if(name=='yy'){
                this.msg='CCQ'
             }else{
                this.msg='请充钱'
             }
          },
          //一进入页面就监听
           immediate:true
          }
       }
    
    
复制代码

动态路由params传参

    index.js文件
          {
            path: '/cldB/:id',
            name: 'cldB',
            props:true,
            component: () => import('../views/CldB.vue'),
          }
     App页面
        <router-link to="/cldB/1">CldB-1</router-link>|
        <router-link to="/cldB/2">CldB-2</router-link>|
     子组件
     props:['id']
        ,
        watch:{
          $route:{
             handler:function(){
                 if(this.$route.params.id==1){
                     this.msg='我是1号'
                 }else if(this.$route.params.id==2){
                     this.msg='我是2号'
                 }else{
                      this.msg='我是3号'
                 }
             },
            immediate:true
          },
        }

           /* 跳转页面两种写法 */
 this.$router.push('/about') 地址path
 this.$router.push({name:'about'}) 地址name

vue全局守卫

你可以使用 router.beforeEach 注册一个全局前置守卫:

const router = new VueRouter({ ... })

router.beforeEach((to, from, next) => {
  // ...
})

当一个导航触发时,全局前置守卫按照创建顺序调用。守卫是异步解析执行,此时导航在所有守卫 resolve 完之前一直处于 等待中。

每个守卫方法接收三个参数:

  • to: Route: 即将要进入的目标 路由对象
  • from: Route: 当前导航正要离开的路由
  • next: Function: 一定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数。