const router = createRouter({ history, routes,})router.beforeEach(async (to, from) => { if (to.path === '/' || to.path.startsWith('/welcome') || to.path.startsWith('/sign_in')) { return true } else { const path = await http.get('/me').then(() => true, () => '/sign_in?return_to=' + to.path) return true }})题目1: 上面的代码每次路由跳转的时间都会调用 me 接口
办理方法:假如我们不想每次路由跳转都调用接口我们可以把接口调用写在表面
const promise = http.get('/me')router.beforeEach(async (to, from) => { if (to.path === '/' || to.path.startsWith('/welcome') || to.path.startsWith('/sign_in') || to.path.startsWith('/start')) { return true } else { const path = await promise.then(() => true, () => '/sign_in?return_to=' + to.path) return path }})题目2:上面接口是只调一次了,但是我们登录乐成后页面不会跳转
缘故起因:以登录乐成后跳转 http://localhost:8082/#/sign_in?return_to=/items/create 为例,我们的 /me 接口依赖 jwt,没登录就没有 jwt,以是一开始我们未登录从 items/create 跳到 sign_in 没题目,但是登录乐成后由于我们的 /me 接口只在初始化的时间调用,以是纵然我们登录乐成这个接口还是走的一开始的 catch 以是还是跳到了登录页
办理方法:在用户登录乐成乐成后主动去更新
import { AxiosResponse } from "axios";import { http } from "./Http";export let mePromise: Promise<AxiosResponse<{ resource: { id: number }}>> | undefinedexport const refreshMe = () => { mePromise = http.get<{ resource: { id: number }}>('/me') return mePromise}export const fetchMe = refreshMe
// 点击登录按钮后refreshMe()router.push(returnTo || '/')
import { mePromise, fetchMe } from './shared/me';fetchMe()router.beforeEach(async (to, from) => { if (to.path === '/' || to.path.startsWith('/welcome') || to.path.startsWith('/sign_in') || to.path.startsWith('/start')) { return true } else { const path = await mePromise!.then(() => true, () => '/sign_in?return_to=' + to.path) return path }}) |