vue路由组件传参-页面通信
vue路由传参,是页面通信的重要组成部分,而掌握路由传参,必须要认识一个重要对象-$route。(切记,是$route,而不是$router)$route对象这是一个专门用于记录vue组件参数的对象。例如://router.js{ path:'/main/:id',component:Main }router-link中:<router-link to='/...
·
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 }
<完>
更多推荐
已为社区贡献11条内容
所有评论(0)