微参考 vue 如何使用Vue获取URI

如何使用Vue获取URI

在Vue.js中,获取当前页面的URI(Uniform Resource Identifier,统一资源标识符)是一项常见的需求。这通常涉及到获取路由信息或查询字符串参数。下面将详细介绍在Vue应用中获取URI的几种方法。

使用Vue Router获取路径信息

如果你的Vue应用使用了Vue Router,那么你可以很容易地通过路由对象获取当前路径信息。

获取当前路由的路径:

// 在组件内

export default {

mounted() {

const currentPath = this.$route.path;

console.log(currentPath); // 输出当前路由的路径(不包含查询参数)

}

}

获取当前路由的完整URI:

// 在组件内

export default {

mounted() {

const currentFullUri = this.$route.fullPath;

console.log(currentFullUri); // 输出包含查询参数的完整路径

}

}

使用JavaScript获取当前页面的完整URI

如果不使用Vue Router,或者需要获取整个URL(包括协议、域名等),你可以使用JavaScript的内置对象`window.location`。

// 获取当前页面的完整URI

const currentFullUri = window.location.href;

console.log(currentFullUri); // 输出当前页面的完整URI,包括协议、域名、路径和查询参数

获取查询字符串参数

查询字符串参数通常用于GET请求中,你可以使用`window.location.search`或者Vue Router提供的`$route.query`来获取。

使用JavaScript获取查询字符串:

如何使用Vue获取URI

// 获取查询字符串

const searchParams = window.location.search;

// 使用URLSearchParams API解析查询字符串

const urlParams = new URLSearchParams(searchParams);

const myParam = urlParams.get('myParam'); // 获取名为'myParam'的查询参数值

使用Vue Router获取查询参数:

// 在组件内

export default {

mounted() {

const myParam = this.$route.query.myParam; // 获取路由查询参数'myParam'

console.log(myParam);

}

}

总结

在Vue应用中获取URI,你可以根据需要选择不同的方法:

1. 如果只需要获取当前路由的路径或完整路径,使用Vue Router提供的`$route.path`或`$route.fullPath`。

2. 如果需要获取整个页面的完整URI,包括协议和域名,可以使用`window.location.href`。

3. 对于查询字符串参数,你可以使用`window.location.search`结合`URLSearchParams`,或者直接使用Vue Router的`$route.query`。

根据你的具体需求,这些方法可以帮助你方便地获取到当前页面的URI信息。

本文来自网络,不代表微参考立场,转载请注明出处:http://www.weicankao.com/vue/507.html
上一篇
下一篇
返回顶部