首先在組件中導入 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 如果有理解錯誤的請大佬們指出