路由传参方式可划分为 params 传参和 query 传参,而 params 传参又可分为在 url 中显示参数和不显示参数两种方式
方式A :这种需要在路由配置好可以传递参数 xxx 的,不是最方便的
路由配置

1
2
3
4
{
path : '/child/:XXX',
component :( child
}

父组件

1
<router—link to="/child/XXX">:</router—link>

子组件读取

1
this.num = this.$route.params.XXX

方式B :这种同样需要在路山配置好可以传递参数 XXX 的,不过是用到 push方法的
路由配置

1
2
3
4
{
path:'/child/:XXX'
component :Child
}

父组件
this.$router. push({、 /chiId/${XXXFpath :
子组件读取
this.num = this.Sroute.params.XXX上面两种方式都会在地址显示出传递的参数、类似 get 请求方式 c .这种不需要在路由配置好根据路由的名称、需要保持一致路由配置不需要配置,但是子组件的 name 必须与父组件传递的路由一致父组件th iS , $router.push({params :{X)O(: ,1子组件读取this.num = this 、 $route.params.XXX //妈呀方式 D ,这种不需要在路由配置好根据路由的名称`通过 que 缪来传递路由配置不需要配置,但是子组件的 name 必须与父组件传递的路由一致{父组件this.$router.push({path: ‘/child’query: {子组件读取this.num = this.$route.query.XXX总的来说使用方式 C 和 D 最为多,毕竟不需要对路由配置做修改

代码例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!-- ParentComponent.vue -->
<template>
<div>
<h2>Parent Component</h2>
<button @click="goToChildWithParams">Go to Child with Params</button>
<button @click="goToChildWithQuery">Go to Child with Query</button>
</div>
</template>

<script>
export default {
methods: {
// 使用params传参
goToChildWithParams() {
this.$router.push({ path: `/child/${123}` });
},
// 使用query传参
goToChildWithQuery() {
this.$router.push({ path: '/child-query', query: { id: 123 } });
}
}
};
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<!-- ChildComponent.vue -->
<template>
<div>
<h2>Child Component</h2>
<p>Param ID: {{ paramId }}</p>
<p>Query ID: {{ queryId }}</p>
</div>
</template>

<script>
export default {
computed: {
// 获取 params 参数
paramId() {
// this.$route.params.id 是通过路径传递的参数
console.log('Route Params:', this.$route.params);
return this.$route.params.id;
},
// 获取 query 参数
queryId() {
// this.$route.query.id 是通过 query 传递的参数
console.log('Route Query:', this.$route.query);
return this.$route.query.id;
}
}
};
</script>