我有一个具有以下三个简单视图的应用程序:
Homepage - Simple page with information texts
Register - Asks for e-mail and passwords and register users
Logged - When registration done, this page displays buyable items
注册完成后,后端服务器返回令牌,并将其存储到window.localStorage。当浏览器中没有令牌时,我想显示“主页”,如果这样,则应显示“已记录”页面。我也希望它们具有相同的路径:“ /”
如何实现?
router.js
const router = new Router({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{
path: "/",
get component() {
// This code works but when this.$router.push("/") executed from Register, Home is rendered unless page is refreshed
if(typeof Store.getters.token === "undefined") return Home;
return Logged;
},
},
{
path: "/register",
component: Register
}
]
});
register.vue
this.$http.post("register", {
email: this.email,
password: this.password
})
.then(response => {
this.$store.commit("setToken", response.data.token);
this.$router.push("/"); // Homepage is rendered unless page is refreshed
})
答案 0 :(得分:2)
您可以通过以下方式解决这种情况:
Index.vue
<template>
<Homepage v-if="typeof $store.getters.token === 'undefined'"/>
<Logged v-else />
</template>
<script>
import Logged from '../components/Logged'
import Homepage from '../components/Homepage'
export default {
components: {
Logged,
Homepage
},
}
</script>
router.js
const Index = () => import('./views/Index.vue');
const Register = () => import('./views/Register.vue');
const router = new Router({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{
path: "/",
component: Index
},
{
path: "/register",
component: Register
}
]
});