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

使用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"
      }
    });
  }

  • 6
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
获取当前页面的信息,可以使用Vue 3中的$route对象和$router对象。 1. 使用$route对象获取当前页面的路由信息 $route对象包含了当前页面的路由信息,可以通过$route对象的属性来获取当前页面的信息,如下所示: ``` <template> <div> <p>当前页面的路径:{{$route.path}}</p> <p>当前页面的名称:{{$route.name}}</p> <p>当前页面的参数:{{$route.params}}</p> <p>当前页面的查询参数:{{$route.query}}</p> </div> </template> <script> export default { mounted() { console.log(this.$route.path); // 当前页面的路径 console.log(this.$route.name); // 当前页面的名称 console.log(this.$route.params); // 当前页面的参数 console.log(this.$route.query); // 当前页面的查询参数 }, }; </script> ``` 2. 使用$router对象获取当前页面的路由器信息 $router对象包含了整个应用的路由器信息,可以通过$router对象的方法来获取当前页面的信息,如下所示: ``` <template> <div> <p>当前页面的路径:{{currentPath}}</p> <p>当前页面的名称:{{currentName}}</p> <p>当前页面的参数:{{currentParams}}</p> <p>当前页面的查询参数:{{currentQuery}}</p> </div> </template> <script> export default { data() { return { currentPath: "", currentName: "", currentParams: "", currentQuery: "", }; }, mounted() { this.currentPath = this.$router.currentRoute.value.path; // 当前页面的路径 this.currentName = this.$router.currentRoute.value.name; // 当前页面的名称 this.currentParams = this.$router.currentRoute.value.params; // 当前页面的参数 this.currentQuery = this.$router.currentRoute.value.query; // 当前页面的查询参数 }, }; </script> ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值