首先在组件中导入 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 如果有理解错误的请大佬们指出