vue react 动态传参

193 阅读1分钟

vue

1.配置动态路由标识    /:id
{    
     path:'/detail/:id',    // 配置 动态路由标识    
     name:'Detail',   
     component:()=>import('../views/Detail.vue') 
},

2.跳转传参  传真实参数

<button @click='goDetail(item.id)'>跳详情</button>
 goDetail(id){      
     // 点击跳转详情页面       
     // this.$router.push('/detail');  // 动态路由
     this.$router.push(`/detail/${id}`);
 }

3.对应的路由页面获取动态路由传参  this.$route.params.key名

// 获取动态路由参数
console.log(this.$route.params.id);

query传参 配合 path

this.$router.push({path:路由路径,query:{参数}}) // 获取参数 this.$route.query.key名

params传参 配合 name 弊端:页面刷新数据丢失

this.$router.push({name:路由名字,params:{参数}}) // 获取参数 this.$route.params.key名

react

1.在路由配置表配置动态路由标识

 {   
     path:'/detail/:id',   // 配置标识  
     component: Detail   
 },

2.跳转的时候传参 实参

<botton key={index} onClick={()=>{this.goDetail(item)}}>跳详情</botton>
goDetail(item){    
    console.log(this.props);     // 路由跳转  
    // this.props.history.push('/detail');    
    // 路由跳转传参  动态路由     
    // this.props.history.push(`/detail/${item.id}`)   
    // 路由跳转传参  query传参    
    // this.props.history.push({    
    //     pathname:'/detail',     
    //     query:{   
    //         item  
    //  }   
    // })     
    // 路由跳转传参  state传参   
    this.props.history.push({    
        pathname:'/detail',       
        state:{            
            item      
        }   
    }) 
}

3.跳转到的页面获取参数

// 获取动态路由参数
// console.log(this.props.match.params.id);
// 获取query传参
///console.log(this.props.location.query.item);
console.log(this.props.location.state.item);

state传参

// 路由跳转传参    
this.props.history.push({       
    pathname:'/detail',  
    state:{      
        item     
    }   
})     
// 获取参数    this.props.location.state.item

query传参 弊端:页面刷新,数据丢失

// 路由跳转传参    
this.props.history.push({    
    pathname:'/detail',    
    query:{       
        item      
    }   
})    
// 获取参数  
this.props.location.query.item