本文发布于753天前,最后更新于 743 天前,其中的信息可能已经有所发展或是发生改变。
问题复现
当我在两个页面切换时,在setup
函数的子函数里写了const router = useRouter()
,想要以此实现跳转,结果useRouter()
返回了undefined
...
<script> import { reactive } from 'vue' import { useRouter } from 'vue-router' export default { setup(){ const versions = reactive({ ...window.electron.process.versions }) const backToHome=()=>{ const router = useRouter() router.push("/login") } return{ backToHome, versions } } } </script>
或
<script setup> import { reactive } from 'vue' import { useRouter } from 'vue-router' const versions = reactive({ ...window.electron.process.versions }) const backToHome=()=>{ const router = useRouter() router.back() } </script>
原理与解决
useRouter
和useRoute
两个函数必须在setup
函数中或者在<script setup>
的顶层才会返回router
和route
对象
改成
<script> import { reactive } from 'vue' import { useRouter } from 'vue-router' export default { setup(){ const versions = reactive({ ...window.electron.process.versions }) const router = useRouter() const backToHome=()=>{ router.push("/login") } return{ backToHome, versions } } } </script>
或
<script setup> import { reactive } from 'vue' import { useRouter } from 'vue-router' const versions = reactive({ ...window.electron.process.versions }) const router = useRouter() const backToHome=()=>{ router.back() } </script>