在 Vue 3 中获取当前网址的完整 URL 或部分信息,可以通过以下两种方式实现:
一、使用浏览器原生对象 window.location
(不依赖路由)
// 获取完整 URL
const fullUrl = window.location.href;
// 分解 URL 的不同部分
const protocol = window.location.protocol; // 协议 (e.g., "https:")
const hostname = window.location.hostname; // 域名 (e.g., "example.com")
const path = window.location.pathname; // 路径 (e.g., "/page/subpage")
const searchParams = window.location.search; // 查询参数 (e.g., "?id=123")
const hash = window.location.hash; // 哈希值 (e.g., "#section")
二、使用 Vue Router(推荐,支持响应式)
如果你的项目配置了 Vue Router,可以通过路由对象获取当前路径信息:
1. 在模板中直接使用 $route
<template>
<div>
当前路径:{{ $route.path }}
查询参数:{{ $route.query }}
</div>
</template>
2. 在组合式 API(setup
)中使用
import { useRoute } from 'vue-router';
export default {
setup() {
const route = useRoute();
// 响应式路径信息
console.log('路径:', route.path);
console.log('查询参数:', route.query); // 如 ?id=123 → { id: '123' }
console.log('哈希值:', route.hash); // 如 #section → '#section'
return { route };
}
};
关键区别
特性 | window.location | Vue Router ($route ) |
---|---|---|
响应式 | ❌ 不会自动更新 | ✅ 路由变化时自动更新 |
单页应用兼容性 | ❌ 直接修改会刷新页面 | ✅ 无刷新跳转 |
获取完整 URL | ✅ 包含协议、域名等 | ❌ 仅路由路径部分 |
依赖路由库 | ❌ 无需 Vue Router | ✅ 需要安装 Vue Router |
使用建议
- 需要操作 路径、查询参数、哈希 且项目已配置路由时,优先使用
useRoute
。 - 需要获取 完整 URL 或域名信息 时,使用
window.location
。
如果需要监听 URL 变化,可以使用路由的导航守卫或 watch
监听 route
对象:
watch(
() => route.path,
(newPath) => {
console.log('路径变化:', newPath);
}
);