vue页面跳转的方式(自己记录)

本文介绍Vue.js中使用router-link组件及this.$router方法进行页面跳转的方式,包括无参数、带参数的跳转方法,并区分了query与params的不同用途。此外,还介绍了如何利用路由守卫控制页面的访问权限。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.router-link跳转

//不带参数
<router-link to = '/index'>
	<button>go</button>
</router-link>
//带参数
<router-link to = "{path: 'index',query:{id:123456}">
	<button>go</button>
</router-link>
<router-link to = "{path: 'index',params:{id:123456}">
	<button>go</button>
</router-link>

2:this. r o u t e r . p u s h ( ) t h i s . router.push() this. router.push()this.router全局的路由对象,包含路由相关的属性、对象 (如 history 对象) 和方法,在任何页面都可以通过 this. r o u t e r 调 用 其 方 法 如 p u s h ( ) 、 g o ( ) 、 r e s o l v e ( ) 等 。 t h i s . router 调用其方法如 push() 、go() 、resolve() 等。 this. routerpush()go()resolve()this.route 表示当前的路由对象。每一个路由都有一个 route 对象,它是一个局部的对象,可以获取当前路由对应的 name , params, path , query 等属性。
push方法调用:

  • this.$router.push 跳转到指定url路径,history栈将添加一个记录,点击后退会返回到上一个页面
  • this.$router.replace 跳转到指定url路径,直接替换当前页面,点击返回则会跳转到原始页面的上个页面
  • this.$router.go(n) 向前或者向后跳转n个页面,n可为正整数或负整数
//字符串
this.$router.push('home') //->/home

//对象
this.$router.push({path:'home'}) //->/home

//命名的路由
this.$router.push({name:'user', params:{userId: '123'}}) //->/user/123

//带查询参数,变成 /register?plan=private
this.$router.push({path:'register', query:{plan:private}}) 

const userId = '123';
//这里的 params 不生效
this.$router.push({path:'/user', params:{userId}});  //->/user`


//跳转函数
go(){
	this.$router.push('/index')
	//take with params
	this.$router.push({name:'index';params :{id:123456}})
	this.$router.push({path:'index';query:{id:123456}})
}
this.$router.go(-1)//goback 
this.$router.go(1)//go ahead

params和query的区别就是query在浏览器地址栏中显示参数,params则不显示

path 和 Name都可以用query传参
params只能对应name
query相当于get请求
params相当于post请求

path-query: localhost:8080/#/index?id = 123456
name-params: localhost:8080/#/index

3.a标签可以跳转外部列链接但是不能路由跳转,同时路由可以通过this.$route.query.idthis.$route.params.id来进行参数获取

tips1:
路由守卫:根据状态判断是否进行路由跳转


router.beforeEach((to, from, next) => {
  // ...
})

/*example:
	to:下一个页面
	from:即将离开的页面
*/
router.beforeEach((to, from, next) => {
  if (to.path == '/login') {
    sessionStorage.removeItem('user');
  }
  let user = JSON.parse(sessionStorage.getItem('user'));
  if (!user && to.path != '/login') {
    next({ path: '/login' })
  } else {
    next()
  }
})

tips2:

跳转路径是否携带/ 区别就是选择的路径不同。因为加“/”的意思是根目录下的绝对路径,不加“/”的意思是当前目录下的相对路径。
HTML字符可以用一些代码来表示,代码可以有2种表示方式。即字符代码(命名实体)和数字代码(编号实体)。
example:
当前页面:http://localhost:8080/demo/page
“/index”=>"http://localhost:8080/index
"index.com => “http://localhost:8080/demo/page/index”

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值