接着上一个工程写带有参数请求的路由跳转
一、
1.主页面 Main.vue 传递参数
<el-menu-item index="1-1">
<!--插入的地方-->
<router-link :to="{name:'UserProfile',params:{ id:1,name:'swk'}}">个人信息</router-link>
</el-menu-item>
<el-menu-item index="1-2">
<!--插入的地方-->
<router-link to="/user/list">用户列表</router-link>
</el-menu-item>
name:传递的组件名
params:传递参数
改成了:to ,即将这一属性绑定成对象
2.路由配置 index.js 里
children:[
{
path:'/user/profile/:id/:name',
name:'UserProfile',
component:Profile
},
{
path: '/user/list',
component: List
}
]
添加name 与上面组件名一致
/:id 添加参数占位符
3.在组件页 Profile.vue 中
<template>
<div>
<h1>个人信息</h1>
<h1>{{$route.params.id}}</h1>
<h1>{{$route.params.name}}</h1>
</div>
</template>
<script>
export default {
name: "UserProfile"
}
</script>
<style scoped>
</style>
注意:template中 只能有一个元素结点
使用 $route.params.id 来获得参数id的值
4.结果:

二、解耦方式
1.路由配置 index.js 中 添加支持传递参数
children:[
{
path:'/user/profile/:id/:name',
name:'UserProfile',
// 支持传递参数
props:true,
component:Profile
},
{
path: '/user/list',
component: List
}
]
2.同样在Main.vue 中
<el-menu-item index="1-1">
<!--插入的地方-->
<router-link :to="{name:'UserProfile',params:{ id:1,name:'swk'}}">个人信息</router-link>
</el-menu-item>
<el-menu-item index="1-2">
<!--插入的地方-->
<router-link to="/user/list">用户列表</router-link>
</el-menu-item>
3. 在 组件页 Profile.vue 中
<template>
<div>
<h1>个人信息</h1>
<h1>{{$route.params.id}}</h1>
<h1>{{$route.params.name}}</h1>
<h2>{{id}}</h2>
<h2>{{name}}</h2>
</div>
</template>
<script>
export default {
props:['id','name'],
name: "UserProfile"
}
</script>
<style scoped>
</style>
4.运行结果:

三、重定向
下面写一个重定向到首页的goHome路由路径
1. 在路由配置 index.js 中 添加一条
{
path: '/goHome',
redirect:'/main'
}
2. 主页面 Main.vue 中 添加
<el-menu-item index="1-3">
<!--插入的地方-->
<router-link to="/goHome">回到首页</router-link>
</el-menu-item>
3.运行结果

点击回到首页,显示

重定向成功!
本文详细介绍了Vue中如何进行参数传递和重定向。在Main.vue中通过name和params传递参数,路由配置文件index.js中设置对应的路由规则。在Profile.vue组件中,通过$route.params获取传入的参数。此外,还探讨了解耦参数传递的方法。最后,展示了如何在Vue中实现重定向到首页的操作。
 参数传递及重定向&spm=1001.2101.3001.5002&articleId=117532146&d=1&t=3&u=3eab1b24505849e6aab1b501a7ac34b8)
8283

被折叠的 条评论
为什么被折叠?



