Home > Blockchain >  Conditionally rendering component in router view
Conditionally rendering component in router view

Time:05-10

I'm working on Vue3 and I'm new to VueJS. So I have an App.vue component by default where all components rendering, but I have a Login.vue and I don't want to render the <header></header> part for the login.vue. Consider Login.vue as a static component!

App.vue

<template>
      <header >
        <img alt="Vue logo"  src="@/assets/logo.svg" width="125" height="125" />

        <div >
          <HelloWorld msg="Knowledge Base System for IFIC Bank" />

          <nav>
            <RouterLink to="/">Home</RouterLink>
            <RouterLink to="/about">About</RouterLink>
            <RouterLink to="/login">login</RouterLink>
          </nav>
        </div>
      </header>

    <RouterView/>
</template>

CodePudding user response:

I think the best way is to use the meta of your route. This way, the solution is reusable in other contexts and not specific to the login route.

const router = new VueRouter({
  routes: [
    {
      path: '/login',
      component: Header,
      meta: { hideHeader: true }
    }
  ]
})

and add a v-if with !route.meta.hideHeader

<script setup>
    import { useRoute } from "vue-router";
    let route = useRoute();
</script>

<template>
  <header v-if="!route.meta.hideHeader">
    <img alt="Vue logo"  src="@/assets/logo.svg" width="125" height="125" />

    <div >
      <HelloWorld msg="Knowledge Base System for IFIC Bank" />

      <nav>
        <RouterLink to="/">Home</RouterLink>
        <RouterLink to="/about">About</RouterLink>
        <RouterLink to="/login">login</RouterLink>
      </nav>
    </div>
  </header>
</template>

CodePudding user response:

<script>
import { useRoute } from "vue-router";
export default {
  setup() {
    let route = useRoute();
    return { route };
  }
};
</script>

or setup

<script setup>
import { useRoute } from "vue-router";
let route = useRoute();
</script>

And then your template

<template>
  <header v-if="route.path !== '/login'">
    <img alt="Vue logo"  src="@/assets/logo.svg" width="125" height="125" />

    <div >
      <HelloWorld msg="Knowledge Base System for IFIC Bank" />

      <nav>
        <RouterLink to="/">Home</RouterLink>
        <RouterLink to="/about">About</RouterLink>
        <RouterLink to="/login">login</RouterLink>
      </nav>
    </div>
  </header>

<RouterView/>

Use useRoute, return it in your setup function.

Now you can use route.path and an v-if

CodePudding user response:

You could extract the header into a component and pass it down into the other components. There you could either use the header component or not.

  • Related