Vue与React编程式路由导航

13 篇文章 0 订阅

一、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>
	)
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值