vue获取当前路由的几种方式
第一种
import { defineComponent,ref} from 'vue'; import { useRouter } from 'vue-router'; const router=useRouter //通过实例化useRouter的router对象中,含有多个属性,其中就包含了当前路由地址, console.log('router',router.currentRoute.value.fullPath);
第二种
import { getCurrentInstance } from 'vue'; const { proxy }: any = getCurrentInstance(); console.log(proxy.$router.currentRoute.value.fullpath);
通过getCurrentInstance 获取当前的组件实例,从而通过其获取router,然后胡德当前路由地址
(图片来源网络,侵删)
第三种
import { toRaw} from 'vue'; import { useRouter } from 'vue-router'; let router = useRouter() console.log(toRaw(router).currentRoute.value.fullPath); 通过toRaw返回其原始对象,即将实例化的router转化为useRouter
第四种
import { watch } from 'vue'; import { useRouter } from 'vue-router'; let router = useRouter() watch(router,(newValue, oldValue) => { console.log(newValue.currentRoute.value.fullPath);}, { immediate: true } ); //这一种写法比较麻烦,但是逻辑比较简单,通过监听获取最新的router对象,进而获取路由地址,而且在第一次的时候,就要执行监听,
第五种
import { ref } from 'vue'; import { useRoute } from 'vue-router'; let path=ref("") const route=useRoute() path.value=route.path //这一种最为简单,推荐这种
(图片来源网络,侵删)
(图片来源网络,侵删)
文章版权声明:除非注明,否则均为主机测评原创文章,转载或复制请以超链接形式并注明出处。
还没有评论,来说两句吧...