好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

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获取当前路由地址内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

查看更多关于vue3获取当前路由地址的两种方法的详细内容...

  阅读:95次