【发布时间】:2022-12-10 13:49:59
【问题描述】:
当我在 AuthCallback 组件中调用路由器函数时出现错误 Cannot access 'AuthCallback' before initialization,这是怎么回事? 我需要的功能是 - 当用户登录时,他被转移到回调页面,然后立即转移到配置文件页面,但这是我尝试连接路由器时遇到的错误
路由器.ts
import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router'
import main from '../layout/main-layout.vue'
import AuthCallback from '../components/user/user-interact/user-callback.vue'
import Profile from '../components/user/user-profile/user-profile.vue'
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
name: 'main',
component: main
},
{
path: '/callback/:',
name: 'AuthCallback',
component: AuthCallback
},
{
path: '/id/:usedId',
name: 'Profile',
component: Profile
}
]
})
export default router
用户回调.vue
<script lang="ts">
import { useRoute } from 'vue-router';
import router from '../../../router/index.ts';
import { store } from '../../../stores/userState.ts'
export default {
name: 'AuthCallback',
mounted() {
const tokenParseRegex: RegExp = /access_token=(.*?)&/;
const idParseRegex: RegExp = /user_id=(.*?)$/;
const exAccessToken: RegExpMatchArray | null = useRoute().hash.match(tokenParseRegex);
const exUserId: RegExpMatchArray | null = useRoute().hash.match(idParseRegex);
if (exAccessToken![1] !== null) {
store().userState.accessToken = exAccessToken![1];
store().userState.userId = exUserId![1];
store().userState.isAuthorized = true;
} else {
return
}
if (store().userState.accessToken !== null) {
console.log(router()) // if i remove this line - all be fine
}
}
}
</script>
【问题讨论】:
-
这就是 useRouter 的用途。不要无故直接导入路由器。类似于 stackoverflow.com/a/73792874/3731501 。另外
router不是函数,不应该是router() -
@EstusFlask,那么我应该如何使用 router.push()?
标签: typescript vue.js vue-router