Vue-params和query传参,组件路由钩子

130 阅读1分钟

params传参

不采用动态路由的方式 第一次id是可以发送出去的
用params传值 只能采用name形式 不能采用path方式
params传参 参数不会在地址栏展示出来 不会触发组件更新钩子函数
goAbout(){

          this.$router.push({
            name:'about',
            params:{
              id:1000
            }
          })
用缓存的办法解决刷新不显示的办法

            created(){
            if(this.$route.params.id){
              localStorage.id=this.$route.params.id
            }
            let id=localStorage.id||this.$route.params.id
            console.log(id);
          }

query传参

     采用query的方式传参比params好,刷新之后不会消失 
     id传过去是数字类型,刷新之后是字符串类型

         相比较于params,好在刷新之后不会消失          query传值可以采用path方式,params不行          query传参 参数会在地址栏展示出来 *

            this.$router.push({
            /* path:'/vip', */
            name:'VipPage',
            query:{
              id:1
            }
          })
    在组件中可以直接用this.$route.query.id获取参数
    

路由返回上一页 刷新 下页 替换

        返回上一页
        this.$router.go(-1)
        刷新
        this.$router.go(0)
        返回下一页
        this.$router.go(1)
        替换
        this.$router.replace('/about')
        
        

组件内的路由钩子函数

          组件内的钩子函数 里面next()方法必须执行一次
          
          进入时触发
          beforeRouteEnter(to, from, next) {  
          守卫执行前 组件实例还没有被创建
           那怎么获取this呢,vm就是获取的this
              next(vm=>{
                console.log('vm',vm);
             })
          }
          
          离开时触发
          beforeRouteLeave(to, from, next) {
              next();      
          }
          
          更新时触发
          beforeRouteUpdate(to, from, next) {               
              next();