vueRouter4.0 编程式导航的使用方法

首先在组件中导入 getCurrentInstance

1 import {
2   defineComponent,
3   reactive,
4   getCurrentInstance // 从此函数的返回值中获取到ctx属性调用$router.push()
5 } from 'vue'

 

然后在setup() 中调用函数

1   setup () {
2     const { ctx }: any = getCurrentInstance()
3     const handleNavClick = (path: string): void => {
4       console.log(path)
5       ctx.$router.push(path)
6     }
7

 

方法2:推荐写法

先引入

import { Router, useRouter } from 'vue-router' // Router 是TS中的接口 js可以不管它

然后在setup() 中调用函数

 setup () {
    const router: Router = useRouter()
    console.log(router)

    const handleNavClick = (path: string): void => {
      console.log(path)
      router.push(path)
    }

    return {
      handleNavClick
    }
  }

 

正在学习vueRouter4.0  如果有理解错误的请大佬们指出

posted @ 2021-01-10 20:26  祁腾飞  阅读(1362)  评论(1编辑  收藏  举报