一、Vue
1、作用:不借助<router-link>
实现路由跳转,让路由跳转更加灵活
2、具体编码:
//$router的两个API
this.$router.push({
name:'xiangqing',
params:{
name:xxx,
age:xxx
}
})
this.$router.replace({
name:'xiangqing',
params:{
name:xxx,
age:xxx
}
})
this.$router.forward() //前进
this.$router.back() //后退
this.$router.go() //可前进也可后退
二、React
1、react-router-dom@5
1、作用:不借助<Link>
实现路由跳转,让路由跳转更加灵活
2、具体编码:
replaceShow = (name,age)=>{
//replace跳转+携带params参数
this.props.history.replace(`/home/message/detail/${name}/${age}`)
//replace跳转+携带search参数
this.props.history.replace(`/home/message/detail?id=${name}&title=${age}`)
//replace跳转+携带state参数
this.props.history.replace(`/home/message/detail`,{name,age})
}
pushShow = (id,title)=>{
//push跳转+携带params参数
this.props.history.push(`/home/message/detail/${name}/${age}`)
//push跳转+携带search参数
this.props.history.push(`/home/message/detail?name=${name}&age=${age}`)
//push跳转+携带state参数
this.props.history.push(`/home/message/detail`,{name,age})
}
back = ()=>{
this.props.history.goBack()
}
forward = ()=>{
this.props.history.goForward()
}
go = ()=>{
this.props.history.go(-2)
}
2、react-router-dom@6
import {useNavigate} from 'react-router-dom'
export default function Message() {
const navigate = useNavigate()
function showDetail(name,age) {
navigate('detail',{
replace: false,
state: { // 只能写state参数,其他类型的参数拼接到路径后即可
name,
age
}
})
}
function back() {
navigate(-1)
}
function forward() {
navigate(1)
}
return (
<button onClick={showDetail(name,age)}>查看详情</button>
<button onClick={back}>后退</button>
<button onClick={forward}>前进</button>
)
}