Router传参的几种方式

2022/7/26 6:52:55

本文主要是介绍Router传参的几种方式,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

一、普通不携带参数

  1. 父组件代码
<!-- app.vue -->

<router-link to="/user">
  1. 路由配置
// router/index.js

{
  path: '/user',
  name: 'User',
  component: User
}
  1. 导航栏显示
http://localhost:8082/#/user

二、携带参数的几种方法

  1. 父组件代码
<!-- app.vue -->

<router-link :to="`/user/${id}`">

<script>
data() {
  return {
    id:123
  }
}
</script>
  1. 路由配置
// router/index.js

{
  path: '/user/:id',
  name: 'User',
  component: User
}
  1. 导航栏显示
http://localhost:8082/#/user/123
  1. 子组件获取
// 通过 $route.params 获取所有传递的参数对象
this.$route.params
// 通过指定key值获取准确的参数
this.$route.params.id

$router.push()

通过点击触发,直接跳转到指定页面

  1. 父组件代码
<!-- app.vue -->

<button @click="goUser(456)">this.$router.push()-传参</button>

<script>
data() {
  methods: {
    goUser(id) {
      this.$router.push({
	// 直接访问地址,类似第一种方式,只是一个是路由组件,一个是点击事件触发
        path: `/user/${id}`
      })
    }
  }
}
</script>
  1. 路由配置
// router/index.js

{
  path: '/user/:id',
  name: 'User',
  component: User,
}
  1. 导航栏显示
http://localhost:8082/#/user/456
  1. 子组件获取
// 通过 $route.params 获取所有传递的参数对象
this.$route.params
// 通过指定key值获取准确的参数
this.$route.params.id

params

params 只能与 name 一起使用

跳转后不会将参数拼接到 url 上,刷新页面后参数会丢失

  1. 父组件代码
<!-- app.vue -->

<button @click="goUser(789)">params-传参</button>

<script>
data() {
  methods: {
    goUser(id) {
      this.$router.push({
	// name 必须与路由的 name 一致
        name: 'User',
        params: {
          id
        }
      })
    }
  }
}
</script>
  1. 路由配置
// router/index.js

{
  path: '/user',
  name: 'User',
  component: User,
}
  1. 导航栏显示
http://localhost:8082/#/user
  1. 子组件获取
// 通过 $route.params 获取所有传递的参数对象
this.$route.params
// 通过指定key值获取准确的参数
this.$route.params.id

query

query 可以和 name 或者 path 一起搭配使用

跳转后在 url 后面拼接参数:?id=abc,非重要数据可以这样传,像密码之类使用 params

  1. 父组件代码
<!-- app.vue -->

<button @click="goUser('abc')">query-传参</button>

<script>
data() {
  methods: {
    goUser(id) {
      this.$router.push({
	// 直接填写 path ,或者使用 name
        // path: '/user',
		name: 'User'
	// 传参使用 query
        query: {
          id
        }
      })
    }
  }
}
</script>
  1. 路由配置
// router/index.js

{
  path: '/user',
  name: 'User',
  component: User,
}
  1. 导航栏显示
http://localhost:8082/#/User?id=abc
  1. 子组件获取
// 通过 $route.query 获取所有传递的参数对象
this.$route.query
// 通过指定key值获取准确的参数
this.$route.query.id


这篇关于Router传参的几种方式的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程