Vue , React 路由傳參的幾種方式
Vue路由傳參
方法一:定義路由時直接攜帶
{
path:'/detail/:id/:info/:isTrue/:classList',
name:'detail',
component:Detail
}
? ? 獲取:this.$route.params
注:參數會被全部轉化成字符串,地址欄可見。頁面刷新后參數不會消失。
方法二:通過params
this.$router.push({
path:`/describe/${id}`,
})
用params 時,需要在定義路由時需要在path中添加/:id來對應 $router.push 中path攜帶的參數。
{
path:'/describe/:id',
name:'Describe',
component:Describe
? }
? ? 獲?。簍his.$route.params.id
注:params可以攜帶任意類型數據,參數在地址欄不可見。刷新后參數消失
方法三:通過query
this.$router.push({
????path:'/describe',
????query:{
????????id:id
? ? ? ?? }
?})
? ? 獲?。簍his.$route.query.id
注:參數在地址欄顯示。在進行頁面刷新時,所有參數值會轉換成字符串。如果參數攜帶布爾值,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'? )
接收頁面接收參數
通過? 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' } })
? ? 接收頁面參數:
? ? 通過 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'} })
? ? 接收頁面參數:
? ? 通過? this.props.location.query.name