×

vue3小技巧:分享获取当前路由地址方法

作者:andy0012023.01.09来源:Web前端之家浏览:5435评论:0
关键词:vue3

vue3小技巧:分享获取当前路由地址方法。

很多程序员不知道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.currentRouteRefImpl对象, 即我们使用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"
     }
   });


您的支持是我们创作的动力!
温馨提示:本文作者系 ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://jiangweishan.com/article/vue320230109a3.html

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

发表评论: