Vue3之路由跳转写法

在Vue3的项目中,我想进行路由跳转,于是使用

this.$router.push("/newCollect")

报Cannot read property '$router' of undefined错误。

原来该语法只能用于method中,而我是在setup函数中进行路由跳转的。

解决方法为:

1.导入useRouter函数

import { useRouter } from "vue-router";

2.在进入setup函数时执行

const router = useRouter()

3.在setup函数中进行路由跳转

不传参写法为:

router.push('/newCollect')

传参写法为:

router.push({
  path: "/newCollect",
  query: {
    mode: "edit",
  },
});

4.在新页面获取参数(需要传参时)

const mode = router.currentRoute.value.query.mode;

 

posted @ 2022-03-15 15:58  罗毅豪  阅读(10488)  评论(0编辑  收藏  举报