【Vue 路由参数传递】


一、使用 params 传递参数

1. 基本路由格式

在Vue中,使用params传递参数是通过路由的动态片段来完成的。在路由配置中,使用:定义一个参数占位符,然后在路由跳转时将实际值传递给参数。

const routes = [
  {
    path: '/user/:id', // 定义参数占位符 ':id'
    component: UserProfile
  }
]

定义一个路由 /user/:id,其中 :id 是参数占位符。在路由跳转时传递实际的用户ID值:

// 在代码中进行路由跳转并传递参数
this.$router.push({ path: `/user/${userId}` })

2. 可选参数的使用

通过在路由定义中使用问号(?)来实现。

const routes = [
  {
    path: '/user/:id?', // 定义可选参数 ':id?'
    component: UserProfile
  }
]

/user/user/:id都可以匹配这个路由。当参数是可选时,如果不提供参数,Vue会将其视为undefined

代码示例

<template>
  <div>
    <h1>User Profile</h1>
    <p v-if="$route.params.id">User ID: {{ $route.params.id }}</p>
    <p v-else>User ID is not provided</p>
  </div>
</template>

<script>
export default {
  mounted() {
    // 获取传递过来的用户ID
    const userId = this.$route.params.id
    if (userId) {
      // 根据用户ID加载用户数据
      this.loadUserProfile(userId)
    } else {
      // 处理没有提供用户ID的情况
      console.log('User ID is not provided')
    }
  },
  methods: {
    loadUserProfile(userId) {
      // 发起API请求或执行其他操作,加载用户数据
      console.log(`Loading data for user ID: ${userId}`)
    }
  }
}
</script>

二、使用 query 传递参数

1. 基本路由格式

params不同,query参数是以键值对的形式附加到URL的查询字符串中的。在路由配置中,不需要定义参数占位符,而是直接在路由跳转时传递参数。

const routes = [
  {
    path: '/user',
    component: UserProfile
  }
]

将参数直接作为查询参数传递:

// 在代码中进行路由跳转并传递参数
this.$router.push({ path: '/user', query: { id: userId } })

代码示例

<template>
  <div>
    <h1>User Profile</h1>
    <p>User ID: {{ $route.query.id }}</p>
  </div>
</template>

<script>
export default {
  mounted() {
    // 获取传递过来的用户ID
    const userId = this.$route.query.id
    if (userId) {
      // 根据用户ID加载用户数据
      this.loadUserProfile(userId)
    } else {
      // 处理没有提供用户ID的情况
      console.log('User ID is not provided')
    }
  },
  methods: {
    loadUserProfile(userId) {
      // 发起API请求或执行其他操作,加载用户数据
      console.log(`Loading data for user ID: ${userId}`)
    }
  }
}
</script>

总结

  • 使用 params 时,参数直接包含在路由的路径中,适用于对参数的格式和可见性有要求的情况。通过在路径中使用问号(?),还可以使某些参数变为可选。
  • 使用 query 时,参数作为查询字符串传递,适用于需要将参数保留在URL中的情况,或者需要传递多个参数的情况。
  • 7
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

武帝为此

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值