Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically show components depending on the current route, vuejs

Tags:

vue.js

In vue how do I dynamically show components based on the current route?

I only want the custom-componentto be visible if not on the homepage. And by default, I set that the user is on the homepage so the component doesn't show on load.

I've tried several router methods with no luck: https://router.vuejs.org/api/#router-instance-methods.

app.vue:

<template>
  <div id="app" :class="$style.app">
    <navbar/>
    <custom-component v-bind:is="homePage"></custom-component>
    <router-view :class="$style.content"/>
    <footer/>
  </div>
</template>


  data() {
    return {
      homePage: true
    }
  },
 methods: {
     homePage() {
  if(this.$route.path("/") || this.$route.path("/home")) {
    this.homePage = true
  } else {
    this.homePage = false
  }
}
}

This is close, but doesn't achieve the desired results: VueJS - Load child components dynamically.

Also would this be the best way to do it in app.vue as I am trying now. Or should I have this logic in the custom-component instead?

like image 1000
runningraptor Avatar asked Dec 18 '22 19:12

runningraptor


1 Answers

Why not using a computed property instead of a method ?

export default {
    computed: {
      homePage() {
        if(this.$route.path == "/" || this.$route.path == "/home" ) {
          return true
        } else {
          return false
        }
      }
    }
  }
like image 68
aarcoraci Avatar answered May 05 '23 10:05

aarcoraci