vue3获取当前路由地址的两种方法
作者:菜鸡上线
近期在做ve3的项目时因为功能需要,需要获取当前路由的地址,下面这篇文章主要给大家介绍了关于vue3获取当前路由地址的两种方法,文中通过实例代码介绍的非常详细,需要的朋友可以参考下
方法一:
// router的 path: "/user/:uid"
<template>
<div>user</div>
<p>uid: {{ uid }}</p>
</template>
<script>
import { defineComponent } from "vue";
import { useRouter } from "vue-router";
export default defineComponent({
name: "User",
setup() {
const router = useRouter();
const uid = router.currentRoute.value.params.uid;
return {
// 返回的数据
uid,
};
},
});
</script>useRouter()返回的是object, 类似于vue2的this.$router
而router.currentRoute是RefImpl对象, 即我们使用ref返回的对象, 通过.value可以访问到当前的路由, 类似于vue的this.$route
使用console.log打印出来看看

方式二:window.location 可以直接获取当前窗口的路径
1.window.location.href(当前URL)
结果:http://www.myurl.com:8866/test?id=123&username=xxx
2.window.location.protocol(协议)
结果:http
3.window.location.host(域名 + 端口)
结果:www.myurl.com:8866
4.window.location.hostname(域名)
结果:www.myurl.com
5.window.location.port(端口)
结果:8866
6.window.location.pathname(路径部分)
结果:/test
7.window.location.search(请求的参数)
结果:?id=123&username=xxx
setup(){
const router = useRouter();
onMounted(() => {
console.log("router",router.currentRoute.value)
if(window.location.pathname=="/askQuestions"){
// if(router.currentRoute.value.path=="/askQuestions"){
console.log("消失;;;;;;")
document.getElementById("navSearch").style.display="none"
}
});
}总结
到此这篇关于vue3获取当前路由地址的文章就介绍到这了,更多相关vue3获取当前路由地址内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
