You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue2.7组合式API中如何获取当前路由?

Vue2.7组合式API中获取当前路由的解决方案

在Vue2.7的组合式API场景下,你可以通过以下两种方式获取当前路由:

方法一:通过getCurrentInstance访问组件实例

利用Vue提供的getCurrentInstance获取组件实例,再通过实例的proxy属性访问$route对象:

import { getCurrentInstance } from 'vue'

export default {
  setup() {
    const instance = getCurrentInstance()
    const currentRoutePath = instance.proxy.$route.path
    console.log('当前路由路径:', currentRoutePath)
    
    // 若需操作路由跳转,同样可通过instance.proxy.$router访问路由实例
    // instance.proxy.$router.push('/new-path')
  }
}

方法二:使用适配的路由组合式函数

Vue2.7已适配vue-router提供的useRoute和useRouter组合式函数,但需确保你的vue-router版本在3.6.0及以上:

import { useRoute } from 'vue-router'

export default {
  setup() {
    const route = useRoute()
    console.log('当前路由路径:', route.path)
    
    // 若需路由操作,导入useRouter即可
    // import { useRouter } from 'vue-router'
    // const router = useRouter()
    // router.push('/new-path')
  }
}

内容的提问来源于stack exchange,提问作者cookie_king

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 22:40:35