vue3 router传参

vue3 router传参

A页面点击按钮后携带参数跳转到B页面

原理

  • 导入router import { useRouter } from "vue-router";
  • A页面传参router.push({})
  • B页面接收route.params.num;

demo

route.js

1
2
{ path: '/A', name:'A',component: () => import('pages/A.vueB') },
{ path: '/B', name:'B',component: () => import('pages/B.vue') }

A页面

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
28
29
<template>
<button @click="go">跳转</button>
</template>
<script>
import { useRouter } from "vue-router";
export default ({
setup(props, ctx) {
//router是全局路由对象,route= userRoute()是当前路由对象
let router = useRouter();
const go=()=>{
router.push({
//传递参数使用params的话,只能使用name指定(在route.js里面声明name)
name:"B",
params:{
num:1
}
/* 使用query的话,指定path或者name都行
path:'/home',
query:{
num:1
} */
})
}
return{
go,
}
}
})
</script>

B页面

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<template>
{{ num }}
</template>
<script>
import { useRoute } from "vue-router";

export default {
setup(props, ctx) {
//router是全局路由对象,route= userRoute()是当前路由对象
let route = useRoute();
const num = route.params.num;
console.log(num);
return {
num,
};
},
};
</script>


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!