【发布时间】:2020-07-28 20:18:54
【问题描述】:
我正在尝试围绕 vue.js 的 Navigation Guards。我试图按照这个例子做,但我认为我在将我的状态(store.js)连接到我的路由器(routes.js)方面做得不够。在我的 Login.vue 组件中,我尝试在 loadUser 分派到 State 之后推送到新路由,随后 isLoggedIn 更新为 true。在我使用 mapState 的 vue 组件中,我是否需要在 routes.js 中做同样的事情。或者也许有更好的方法来做到这一点。为了提供完整的图片,我使用了 vue 前端和 laravel 后端以及 Sanctum。
从 routes.js 中提取
const routes = [
{
path: '/',
component: Login,
name: 'login'
},
{
path: '/dashboard',
component: Dashboard,
name: 'dashboard',
meta: { requiresAuth: true }
},
]
const router = new VueRouter({
mode: 'history',
routes // short for `routes: routes`
});
router.beforeEach((to, from, next) => {
// if (to.matched.some(record => record.meta.requiresAuth)) {
if (to.meta.requiresAuth) {
if (store.state.isLoggedIn) {
next();
} else {
next({
name: 'home'
});
}
} else {
next();
}
});
export default router;
从 store.js 中提取
export default {
state : {
isLoggedIn: false,
}
}
从 Login.vue 中提取
methods : {
async login() {
this.loading = true;
this.errors = null;
try {
await axios.get('/sanctum/csrf-cookie');
await axios.post('/login', this.user);
logIn();
this.$store.dispatch('loadUser');
this.$router.push({ name: 'logbook'});
} catch (error) {
this.errors = error.response && error.response.data.errors;
}
this.loading = false;
}
},
【问题讨论】:
-
也许我应该将重定向从 vue 组件移动到路由器?