如何根据Vuex在同一路径中渲染两个组件?

时间:2019-06-30 16:16:09

标签: vue.js vue-router

我有一个具有以下三个简单视图的应用程序:

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
            })

1 个答案:

答案 0 :(得分:2)

您可以通过以下方式解决这种情况:

  1. 定义两个名为 Homepage Logged 组件并将它们导入一个名为 Index的 view
  2. 在索引视图中,将Logged和Homepage组件放到模板中,并进行 v-if 决定使用Logged或Homepage组件,例如;

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
        }
    ]
});