vue3 获取当前页面路由实例的几种方法

获取路由有四种方法,获取到的path和fullpath的区别是fullpath会携带参数,所以要根据业务需求获取不同的数据项。

第一种

import { defineComponent,ref} from 'vue';
import { useRouter } from 'vue-router';
const router = useRouter()
console.log('router',router.currentRoute.value.fullpath);

第二种

import { defineComponent, ref, getCurrentInstance } from 'vue';
const { proxy }: any = getCurrentInstance();
console.log(proxy.$router.currentRoute.value.fullpath);

第三种

import { defineComponent, ref, toRaw} from 'vue';
import { useRouter } from 'vue-router';
let router = useRouter()
console.log(toRaw(router).currentRoute.value.fullPath);

第四种

import { defineComponent, ref, watch } from 'vue';
import { useRouter } from 'vue-router';
let router = useRouter()
watch(
  () => router,
  (newValue, oldValue) => {
    console.log(newValue.currentRoute.value.fullPath);
  },
  { immediate: true }
);
//在选项参数中指定 immediate: true 将立即以表达式的当前值触发回

Vue3中,有多种方法可以获取当前路由。引用中提到了一种方法,即使用`router.currentRoute.value`来访问当前路由对象。通过`.value`属性可以获取当前路由的信息,类似于Vue2中的`this.$route`。这种方法在使用`ref`返回的对象时非常方便。 引用提供了四种不同的获取当前路由方法。第一种方法是使用`import { useRouter } from 'vue-router'`来导入`useRouter`函数,并通过`router.currentRoute.value.fullpath`来获取完整的路径。 第二种方法是使用`getCurrentInstance`函数来获取当前实例,然后通过`proxy.$router.currentRoute.value.fullpath`来获取完整路径。 第三种方法是使用`toRaw`函数来获取原始的`router`对象,然后通过`toRaw(router).currentRoute.value.fullPath`来获取完整路径。 第四种方法是使用`watch`函数来监听`router`对象的变化,然后在回调函数中通过`newValue.currentRoute.value.fullPath`来获取完整路径。 除此之外,引用还给出了一个示例,展示了在Vue3中如何在组件中获取当前路由的参数。在组件中可以使用`const uid = router.currentRoute.value.params.uid`来获取路由参数。 所以,这里总结了Vue3中获取当前路由几种方法,包括使用`router.currentRoute.value`、`useRouter`、`getCurrentInstance`、`toRaw`和`watch`等。具体使用哪种方法取决于你的业务需求和对路由信息的具体访问方式。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [vue3:获取当前路由地址](https://blog.csdn.net/qq_46617584/article/details/126707927)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* [【vue3】获取当前页面路由的四种方法](https://blog.csdn.net/qq_38974163/article/details/121762708)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码农键盘上的梦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值