16. Vue.js参数传递

本文探讨了在Vue.js中如何通过路由参数进行组件间的数据传递,并介绍了三种不同的参数传递方式:直接使用$route.params,利用props进行解耦,以及在登录后动态显示用户名的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参数传递

示例一

  1. 修改index.js
// ...
export default new Router({
  routes: [
    {
      path: '/main',
      name: 'Main',
      component: Main,
      children: [
        {path: '/user/profile/:id', name: 'UserProfile', component: UserProfile},
        {path: '/user/list', name: UserList, component: UserList}
      ]
    }
  ]
})
  1. 修改Main.vue
                <router-link :to="{name:'UserProfile',params:{id: 1}}">个人信息</router-link>
  1. 修改Profile.vue
    所有的元素在使用时必须放在标签内
<template>
  <div style="float: left;">
    <h1>个人信息</h1>
    <h1>{{$route.params.id}}</h1>
  </div>
</template>
  1. 效果图
    在这里插入图片描述

示例二

props解耦

  1. 修改Profile.vue
<script>
  export default {
    props: ['id'],
    name: "UserProfile"
  }
</script>
  1. 修改index.js
export default new Router({
  routes: [
    {
      path: '/main',
      name: 'Main',
      component: Main,
      children: [
      	//修改了这里
        {path: '/user/profile/:id', name: 'UserProfile', component: UserProfile, props: true},
        {path: '/user/list', name: UserList, component: UserList}
      ]
    }
  ]
})

示例三

登录用户之后,在main页面右上角显示用户名

  1. 修改Login.vue
    methods: {
      onSubmit(formName) {
        // 为表单绑定验证功能
        this.$refs[formName].validate((valid) => {
          if (valid) {
            // 在这里添加参数
            this.$router.push("/main/"+this.form.username);
          } else {
            this.dialogVisible = true;
            return false;
          }
        });
      }
    }
  1. 修改index.js
  routes: [
    {
      path: '/main/:name',
      name: 'Main',
      component: Main,
      children: [
        {path: '/user/profile/:id', name: 'UserProfile', component: UserProfile, props: true},
        {path: '/user/list', name: UserList, component: UserList}
      ],
      props: true
    }
  1. 修改Main.vue
        <el-header style="text-align: right; font-size: 12px">
          <!--...-->
          <span>{{name}}</span>
        </el-header>
<script>
  export default {
    props: ['name'],
    name: "Main"
  }
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值