vue路由传参的几种方式

vue路由传参

1.query传参

传递参数:

 1. 路由跳转并携带query参数,to的字符串写法 messageData是一个变量
 <router-link :to="`/home/news?id=001&message=${messageData}`" ></router-link>
 
 2. 路由跳转并携带query参数,to的对象
 <router-link :to="{
 	path:"/home/news",
 	query:{
 		id:001,
 		message:messageData
 	}
 }" ></router-link>

获取参数:this.$route.query.idthis.$route.query.message

2.params传参

传递参数:

  1. 路由跳转并携带param参数,to的字符串写法 ,首先我们要在路由文件中定义我们要传递的参数
 {
    path: '/home',
    name: 'Home',
    component: Home,
    children:[
    	{
    		name:'HomeNews'
    		path:'news/:id/:title',//二级路由,定义参数,表示第一个参数是id,第二个是message
    		component:News,
    	},
  },

跳转时直接斜杠/后面拼接参数

 1. 路由跳转并携带params参数,to的字符串写法 messageData是一个变量
 <router-link :to="`/home/news/001/${messageData}`" ></router-link> //即{id:001,message:xxx}
  1. 路由跳转并携带params参数,to的对象写法,不需要在路由文件中定义参数
  <router-link :to="{
 	name:"HomeNews", (使用params传参时,必须使用name属性进行路由跳转,不能使用path配置项跳转)
 	params:{
 		id:001,
 		message:messageData
 	}
 }" ></router-link>

获取参数:this.$route.params.idthis.$route.params.message

3.路由props配置

传参配置:
src/router/index.js

 {
    name:'HomeNews'
    path:'news/:id',//二级路由,定义参数,表示第一个参数是id,第二个是message
    component:News,
    // 第一种写法:props值为对象,该对象中所有的key-value最终都会通过props传递给组件news
    // props:{a:1},
    // 第二种写法(只能params):props值为Boolean,为true时把路由收到的`params`参数通过props传递给组件news
    // props:true,
    // 第三种写法:props值为函数,该函数返回的对象中每一组key-value都会通过props传递给组件news
   	props:function(route){
   		return {
   			id:route.query.id,
   			message:route.query.message
   		}
   	},
 },

使用:
New.vue

 export default {
 	props:['id','message']
 	data(){ return {} }
 }
  • 2
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值