Vue2.7组合式中使用router3

本文最后更新于:2023年9月12日 晚上

介绍

众嗦粥汁,在setup的组合式语法中,this是无法获取当前Vue实例的,所以这在Vue2.7项目中使用vue-router@3就成为了困难,如下:

1
2
3
4
<script setup>
// 无效
console.log(this.$router, this.$route)
</script>

vue-router@3版本又不支持hook,所以可以手动封装一个,先看使用:

1
2
3
4
5
6
7
8
9
<script setup>
import { useRouter, useRoute } from "@/views/routerHook"

const router = useRouter()
const route = useRoute()

// 以下正常使用
console.log(router, route)
</script>

这让router3封装后可以更加贴合router4setup中的使用,只需要跳转时,这种方法并不推荐,更推荐直接引入使用

1
2
3
4
5
6
7
<script setup>
import router from '@/router'

const toLogin = () => {
router.push('/login')
}
</script>

routerHook.js

1
2
3
4
5
6
7
8
9
10
11
12
13
import { getCurrentInstance } from 'vue'

// 获取当前实例,如果不存在则报错
const getInstance = () => {
const vm = getCurrentInstance()
if (!vm) throw new Error('只能在setup中使用!')
return vm
}
// 访问router
export const useRouter = () => getInstance().proxy.$router
// 访问route
export const useRoute = () => getInstance().proxy.$route

export const route => getInstance().proxy.$route 这样会导致获取不到实例,必须要在setup中调用

更多问题

getCurrentInstance 主要用于需要额外内部访问的官方 vue 库,而不是用于用户态应用程序代码。它被错误地记录在 WIP v3 文档中,但不再被视为公共 API。

getCurrentInstance()最初记录于 2020 年 10 月 4 日,但后来在 Vue 的创建者(Evan You)对 Composition API 文档的重大重构中于2021 年 8 月 31 日删除了该内容。尽管它从文档中删除,getCurrentInstance()但仍然:

鉴于它是一个未记录的内部 API,请谨慎使用。


Vue2.7组合式中使用router3
https://xin-fas.github.io/2023/09/04/Vue2-7组合式中使用router3/
作者
Xin-FAS
发布于
2023年9月4日
更新于
2023年9月12日
许可协议