vue 笔记(十六) 参数传递及重定向

本文详细介绍了Vue中如何进行参数传递和重定向。在Main.vue中通过name和params传递参数,路由配置文件index.js中设置对应的路由规则。在Profile.vue组件中,通过$route.params获取传入的参数。此外,还探讨了解耦参数传递的方法。最后,展示了如何在Vue中实现重定向到首页的操作。

接着上一个工程写带有参数请求的路由跳转

一、

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.运行结果

点击回到首页,显示

重定向成功!

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值