我的自托管应用程序具有简单的身份验证系统。通过有效的用户名和密码后,我需要重定向路由器视图。
不幸的是,当我打电话给router.push("/")
时,什么都没有发生。
然后,我必须再次单击“登录”或手动重新加载页面,或使用router.go()
。
登录后我无法重新加载所有页面,我只需要更新router-view
。
我搜索了很多问题,但没有答案。
您有什么想法吗?
//router.rs
import Vue from "vue";
import Router from "vue-router";
import Home from "../views/Home.vue";
import LoginPage from "../views/LoginPage.vue";
Vue.use(Router);
export const router = new Router({
mode: "history",
base: process.env.BASE_URL,
routes: [{
path: "/",
name: "home",
component: Home
},
{
path: "/login",
name: "login",
component: LoginPage
},
{
path: "/about",
name: "about",
component: () => import("../views/About.vue")
},
{
path: "*",
redirect: "/"
}
]
});
router.beforeEach((to, from, next) => {
const publicPages = ["/login"];
const authRequired = !publicPages.includes(to.path);
const loggedIn = localStorage.getItem("user");
if (authRequired && !loggedIn) {
next("/login");
} else {
next();
}
});
// fragment of LoginPage.vue
import { userService } from "../services";
export default {
components: {},
data() {
return {
username: "",
password: "",
submitted: false
};
},
computed: {
loggingIn() {
// return this.$store.state.authentication.status.loggingIn;
},
alert() {
return this.$store.state.alert;
}
},
created() {
// reset login status
userService.logout();
},
methods: {
handleSubmit() {
this.submitted = true;
if (this.username && this.password) {
userService.login(this.username, this.password).then(
ok => {
this.$router.push({ path: "/" }, () => {});
},
e => {
console.log(e);
}
);
}
}
}
};
答案 0 :(得分:0)
有趣的事情:
Here我们可以找到beforeEach
的实现,而我使用了它们。而且它不能解决我的问题。
我将上一个next()
的其他形式移至labmda的ond上,并且有效。
// fragmet from docs
router.beforeEach((to, from, next) => {
if (...) {
// this was unnecessary for this explanation
} else {
next() // make sure to always call next()!
}
})
// fragmet from my code
router.beforeEach((to, from, next) => {
if (...) {
// this was unnecessary for this explanation
}
// I removed `else` node for last `next()` call
next() // make sure to always call next()!
})
无论如何,请告诉我next
在else
中时为什么它不起作用...