Vue3获取当前页面相对路径
在Vue 3中,获取当前页面路径可以通过多种方式实现,以下是一些常用的方法:
方法一:使用 useRoute
钩子
Vue Router 提供了 useRoute
钩子,可以用来获取当前路由的信息。这是与 Vue Router 深度集成的方式,推荐在 Vue 3 项目中使用。
- 导入
useRoute
钩子:
import { useRoute } from 'vue-router';
- 在页面组件中使用
useRoute
钩子:
const route = useRoute();
- 获取当前页面路径:
const currentPath = route.path;
方法二:使用 getCurrentInstance
方法
Vue 3 提供了 getCurrentInstance
方法,可以获取当前组件的实例,进而访问 router
实例。这种方法较为灵活,但相对复杂一些。
- 导入必要的模块:
import { getCurrentInstance } from 'vue'; import { useRouter } from 'vue-router';
- 获取当前组件实例和
router
实例:
const instance = getCurrentInstance(); const router = useRouter();
- 获取当前路由对象并获取页面路径:
const currentRoute = router.currentRoute.value; const currentPath = currentRoute.path;
方法三:使用 window.location
对象
如果不使用 Vue Router,还可以通过原生的 window.location
对象来获取当前页面的 URL 路径。这种方法不依赖于 Vue Router,但在处理路由参数或查询参数时可能不如 Vue Router 方便。
- 直接获取当前页面路径:
const currentPath = window.location.pathname;
方法四:使用 this.$route
(传统选项式 API)
在 Vue 3 中,如果你使用的是传统的选项式 API,而不是组合式 API,你可以通过 this.$route
来获取当前路由对象,并从中获取页面路径。
- 在组件的
computed
属性中定义路径:
export default { computed: { currentPath() { return this.$route.path; } } }
- 在模板中使用:
<template> <div>当前页面路径: {{ currentPath }}</div> </template>
总结
在 Vue 3 中获取当前页面路径,最推荐的方法是使用 useRoute
钩子,因为它与 Vue Router 深度集成,能够方便地获取到与路由相关的各种信息。其他方法如 getCurrentInstance
、window.location
和 this.$route
也可以根据具体需求选择使用。