现在我有这段代码
import addToast from '@/utils/toast-queue';
import routes from './routes';
import App from './app';
import './assets/styles/global.scss';
import { jsonRequest } from './utils/requests';
Vue.use(VueRouter);
const router = new VueRouter({ routes });
router.beforeEach(async (to, from, next) => {
const userInfo = await jsonRequest('GET', '/user/info');
const notAuthenticated = userInfo.status !== 200;
if (to.name !== 'login' && notAuthenticated) {
if (to.name === 'survey') {
next({ name: 'survey' });
} else {
addToast('Please login', { type: 'error' });
next({ name: 'login' });
}
} else {
next();
}
});
/* eslint-disable-next-line no-new */
new Vue({
el: '#app',
router,
render: h => h(App)
});
当GET请求来自/user/info
到路径/public/form
时,我希望未经过身份验证的用户被重定向到显示表单的页面。如何在vue.js中实现这一点?我已经在route.js
文件中声明了这样的路由
{
path: '/public/form',
name: 'form',
component: () => import('./views/form'),
}
我像这样更新了beforeEach()
router.beforeEach(async (to, from, next) => {
const userInfo = await jsonRequest('GET', '/user/info');
const notAuthenticated = userInfo.status !== 200;
if (to.name !== 'login' && notAuthenticated) {
if (to.name === 'form') {
next({ name: 'form' });
} else {
addToast('Please login', { type: 'error' });
next({ name: 'login' });
}
} else {
next();
}
});
但似乎不工作
根据文档,您应该使用
return { name: 'Login' };
或
return '/login';
不是
next({ name: 'login' });
与form相同。