Vue 讹蘑, React 路由傳參的幾種方式
Vue路由傳參
方法一:定義路由時直接攜帶
{
path:'/detail/:id/:info/:isTrue/:classList',
name:'detail',
component:Detail
}
? ? 獲热谩:this.$route.params
注:參數(shù)會被全部轉(zhuǎn)化成字符串,地址欄可見粱坤。頁面刷新后參數(shù)不會消失。
方法二:通過params
this.$router.push({
path:`/describe/${id}`,
})
用params 時瓷产,需要在定義路由時需要在path中添加/:id來對應 $router.push 中path攜帶的參數(shù)站玄。
{
path:'/describe/:id',
name:'Describe',
component:Describe
? }
? ? 獲取:this.$route.params.id
注:params可以攜帶任意類型數(shù)據(jù)濒旦,參數(shù)在地址欄不可見株旷。刷新后參數(shù)消失
方法三:通過query
this.$router.push({
????path:'/describe',
????query:{
????????id:id
? ? ? ?? }
?})
? ? 獲取:this.$route.query.id
注:參數(shù)在地址欄顯示尔邓。在進行頁面刷新時晾剖,所有參數(shù)值會轉(zhuǎn)換成字符串。如果參數(shù)攜帶布爾值梯嗽,info齿尽,func,可能會導致使用錯誤灯节。
React 路由傳參的三種方法
方法一:通過params
1.路由表中 <Route path=' /sort/:id '? component={Sort}></Route>
2.link方式 <Link to={ ' /sort/ ' + ' 2 ' }? activeClassName='active'>XXXX</Link>
3.js方式? this.props.history.push(? '/sort/'+'2'? )
接收頁面接收參數(shù)
通過? this.props.match.params.id
方法二:通過state (state 傳參是加密的)
? 1.link方式: <Link to={{ path : ' /sort ' , state : { name : 'sunny' }}}>
? 2.js方式: this.props.history.push({ pathname:'/sort',state:{name : 'sunny' } })
? ? 接收頁面參數(shù):
? ? 通過 this.props.location.state.name
方法三:通過query (query傳參是公開的)
? link方式: <Link to={{ path : ' /sort ' ,query: { name : 'sunny' }}}>
? js方式: this.props.history.push({ path : '/sort' ,query : { name: ' sunny'} })
? ? 接收頁面參數(shù):
? ? 通過? this.props.location.query.name