
很多程序员不知道vue3如何获取当前路由地址,本文详细讲解了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。
方式二:window.location 可以直接获取当前窗口的路径
1.window.location.href(当前url)
结果:http://www.xxx.com:8866/test?id=123&username=xxx
2.window.location.protocol(协议)
结果:HTTP
3.window.location.host(域名 + 端口)
结果:www.xxx.com:8866
4.window.location.hostname(域名)
结果:www.xxx.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" } });




网友评论文明上网理性发言 已有0人参与
发表评论: