vue路由组件传参-页面通信

vue路由传参,是页面通信的重要组成部分,而掌握路由传参,必须要认识一个重要对象-$route。(切记,是$route,而不是$router)

$route对象

这是一个专门用于记录vue组件参数的对象。
例如:

//router.js
{ path:'/main/:id',component:Main }

router-link中:

<router-link to='/main/123'></router-link>
//Main.js
console.log(this.$route.params.id);//123

props传递——布尔模式

如果我们不想使用this.$route.params.id的方式传递id,那么props是一种传递的方式,只需要在路由配置文件中,把props配置为true。就能得到这个id。

如果 props 被设置为 true,route.params 将会被设置为组件属性。

{ path:'/main/:id',component:Main, props: true }

在Main.js中:

//main.js
console.log(this.id);

props传递——对象模式

对象模式是在路由配置的props属性中,是一个对象。

{ path:'/login', component:Login, props: { userName: 'mapbar_front'} }

在Main.js中,我们可以这样使用:

props:['userName'],
created:function(){
    console.log(this.userName);
}

props传递——函数模式

函数模式的路由配置中,props属性是函数,这个函数返回一个对象。这个对象中的key,就是将要传递给Main组件的props。

{ 
    path:'/login', 
    component:Login, 
    props: ()=>{ 
        return{
            userName:'mapbar_front',
            age: 26
        }
    }

}

同样的,这样在Main.js中,也可以获取userName属性和age属性。

在函数模式中,可以有一个参数,这个参数就是route对象,里面存储的是路由的相关携带信息。

//函数
function fun(route){
    return { 
        userName: "mapbar_front",
        age: route.params.age
    }
}
//props
{ path:'/login', component:Login, props: funs }

<完>

  • 1
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值