路由——获取$route,$router的三种方式

摘抄自:https://www.cnblogs.com/mica/p/14756503.html

方法一:在当前.vue中引入vue-router的useRoute, useRouter

<script setup>
import { useRoute, useRouter } from 'vue-router'

let $route=useRoute()
let $router = useRouter()
console.log($route.query, $router);
</script>

方法二:通过const { proxy } = getCurrentInstance()获取当前实例

特别注意:
1. 在ts下会报错报错:...类型“ComponentInternalInstance | null”,两种解决方法:
  1.1. 在前面添加 // @ts-ignore 忽视
  1.2. 报错原因是因为getCurrentInstance()可能是ComponentInternalInstance或者null类型,
        
        那么我们给它断言,说它就是ComponentInternalInstancelet { proxy } = getCurrentInstance() as ComponentInternalInstance   

        或者通过 obj?.attr 的形式(如果没有该属性就算了)
        let { proxy } = getCurrentInstance()
        console.log(proxy?.$router)
    
2. const { ctx } = getCurrentInstance()是错误用法,这里ctx打包后在生产环境下是获取不到的

<script setup>
// @ts-ignore
let { proxy } = getCurrentInstance()
console.log(proxy.$route.query);
</script>

方法三:考虑到在获取上下文和全局挂载实例的时候会用到这个getCurrentInstance,那我们来新建 hooks\useCurrentInstance.ts(在方法二上的拓展)

useGlobalProperties.ts
import { ComponentInternalInstance, getCurrentInstance } from 'vue'
export default function useGlobalProperties() {
    const { appContext } = getCurrentInstance() as ComponentInternalInstance
    const globalProperties = appContext.config.globalProperties  //这是在访问全局变量,全局变量里包含路由$route, $router
    return {
        globalProperties
    }
}

xxx.vue
// 先引入文件
import useCurrentInstance from "@/hooks/useCurrentInstance";
...
//使用
const { globalProperties } = useCurrentInstance()
console.log(globalProperties.$route.query);

route:

router

posted on   In-6026  阅读(1709)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示