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  如果有理解錯誤的請大佬們指出


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM