Vue路由传参和接参如何实现

在Vue中,使用Vue Router进行页面路由跳转时,经常需要传递参数到目标页面(组件)并在目标页面(组件)中接收这些参数。Vue Router提供了几种方式来实现路由传参和接参,主要包括通过URL的查询参数(query)、动态路由匹配(params)以及命名路由配合paramsquery使用。下面将分别介绍这几种方式。

1. 通过查询参数(Query Parameters)

传参

使用$router.push<router-link>to属性,并将参数放在URL的查询字符串中。

// 使用编程式导航  
this.$router.push({ path: '/foo', query: { userId: 123 }})  
  
// 使用声明式导航  
<router-link :to="{ path: '/foo', query: { userId: 123 }}">Go to Foo</router-link>
接参

在目标组件中,可以通过this.$route.query来获取这些参数。

export default {  
  mounted() {  
    // 访问查询参数  
    console.log(this.$route.query.userId) // 输出: 123  
  }  
}

 

2. 通过动态路由匹配(Dynamic Route Matching)

定义路由

首先,在路由配置中定义动态片段。

const routes = [  
  { path: '/user/:id', component: User }  
]
传参

使用$router.push<router-link>to属性,并将动态片段的值作为参数。

// 使用编程式导航  
this.$router.push({ name: 'user', params: { id: 123 }}) // 注意:这里应该是query或path,但path需要包含实际的:id值  
this.$router.push('/user/123') // 更直接的方式  
  
// 使用声明式导航  
<router-link :to="{ name: 'user', params: { id: 123 }}">Go to User</router-link> // 错误使用,应使用path或name与query  
<router-link to="/user/123">Go to User</router-link> // 正确
接参

在目标组件中,通过this.$route.params(对于星号片段)或this.$route.params.id(对于普通动态片段)来获取参数。但请注意,对于普通的动态片段(如上面的/user/:id),你应该使用this.$route.params.id,但Vue Router实际上在内部使用this.$route.params来存储星号片段的匹配结果,对于普通的动态片段,参数是通过解析URL得到的,并可以直接通过this.$route.params访问(但通常我们会说它存储在$route.params.xxx中,这里的xxx是动态片段名),但更常见的做法是直接从$route对象上访问解析后的URL片段作为属性(如this.$route.params.id),然而,对于这种情况,实际上应使用this.$route.params.id的前提是你在路由配置中使用了*(星号)匹配,并且配合了children路由,或者使用了alias等特殊配置。对于简单的动态路由匹配(如上例),我们通常通过this.$route.params直接访问到的将是undefined(因为Vue Router并没有特别地将它存储在$route.params下,而是直接通过URL解析得到的),我们实际上应该通过URL的结构来访问它,但在这个场景下,因为它是作为URL的一部分被解析的,所以我们通常不需要显式地“接参”,因为它已经作为路由的一部分被解析并传递给了组件。然而,为了说明如何“接参”,我们可以这样做(尽管这实际上是不必要的):

export default {  
  mounted() {  
    // 访问动态片段  
    if (this.$route.params.id) {  
      // 注意:对于简单的动态路由匹配,这里通常不会有任何输出  
      // 因为this.$route.params.id在这种情况下是undefined  
      // 但如果使用了星号片段或其他特殊配置,这里可能会有值  
      console.log(this.$route.params.id)  
    }  
    // 更常见的做法是直接从$route对象上访问动态片段  
    console.log(this.$route.params.id || this.$route.path.split('/').pop()) // 输出: 123(对于'/user/123')  
  }  
}

 注意:上面的`this.route.params.id∣∣this.route.

相关推荐

  1. Vue如何实现

    2024-07-12 03:50:02       24 阅读
  2. Vue

    2024-07-12 03:50:02       46 阅读
  3. vue3

    2024-07-12 03:50:02       25 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-12 03:50:02       50 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-12 03:50:02       54 阅读
  3. 在Django里面运行非项目文件

    2024-07-12 03:50:02       43 阅读
  4. Python语言-面向对象

    2024-07-12 03:50:02       54 阅读

热门阅读

  1. android轮播图入门2——触摸停止与指示器

    2024-07-12 03:50:02       19 阅读
  2. Symfony 是一个用于构建PHP的框架

    2024-07-12 03:50:02       22 阅读
  3. 利用反射API时的代码注入风险与防护指南

    2024-07-12 03:50:02       17 阅读
  4. python为什么慢?(自用)

    2024-07-12 03:50:02       18 阅读
  5. F1-score

    2024-07-12 03:50:02       15 阅读