Vue.js 是一种流行的前端框架,它让开发者能够高效地构建用户界面和单页面应用程序。在 Vue 应用中,获取当前页面的网址(URL)是一个常见的需求,这可以通过多种方式实现。
使用 `window.location`
最基础的方式是使用原生 JavaScript 中的 `window.location` 对象。这个对象包含了与当前页面的 URL 相关的信息。
// 获取完整 URL
const currentURL = window.location.href;
// 获取协议(如 HTTP 或 HTTPS)
const protocol = window.location.protocol;
// 获取主机名和端口号(如果有的话)
const host = window.location.host;
// 获取路径名
const pathname = window.location.pathname;
// 获取查询字符串
const search = window.location.search;
// 获取哈希值
const hash = window.location.hash;
在 Vue 组件中
在 Vue 组件中,可以通过相同的 `window.location` 对象来获取 URL,或者你可以使用 Vue 实例中的 `$route` 对象(如果你使用的是 Vue Router)。
使用 Vue Router
当你在 Vue 应用中使用 Vue Router 时,你可以通过 `$route` 和 `$router` 这两个对象访问当前路由的信息。
export default {
name: 'App',
methods: {
getURL() {
// 获取当前路由的完整路径
const currentRoute = this.$route.path;
// 获取完整 URL,包括查询参数
const currentFullURL = this.$router.resolve({
name: this.$route.name,
params: this.$route.params,
query: this.$route.query
}).href;
// 打印出来
console.log(currentRoute); // 输出路由路径
console.log(currentFullURL); // 输出完整 URL
}
}
}
不使用 Vue Router
如果你的 Vue 应用没有使用 Vue Router,你仍然可以通过全局属性或方法来访问 URL。
export default {
name: 'App',
created() {
this.getCurrentURL();
},
methods: {
getCurrentURL() {
this.currentURL = window.location.href;
console.log(this.currentURL);
}
}
}
在计算属性中获取 URL
你也可以在 Vue 组件的计算属性(computed properties)中获取 URL,这在需要根据 URL 变化来更新数据时特别有用。
export default {
name: 'App',
computed: {
currentURL() {
return window.location.href;
}
}
}
获取当前页面的 URL 是前端开发中的基本操作,Vue.js 提供了多种灵活的方法来实现这一需求。开发者可以根据应用的具体情况选择最合适的方式。