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
相关产品推荐
相关产品推荐

