Benjamin Landry
Benjamin Landry

Reputation: 3

Disable a component in a specific case in Vue.js

I looked for how to do it but I did not find an answer to my problem anywhere.

Let me explain, I have my page in which I load a component I created 'date-picker'. I need it in most of the components I will load in the router-view. My problem is that I would, if possible, disable it when I load a specific component in the router-view.

<main>
  <date-picker></date-picker>
  <router-view></router-view>
</main> 

Is there a solution, other than nesting my 'date-picker' component in the components they use? I use Vuex if it helps.

Thanks in advance.

Upvotes: 0

Views: 5335

Answers (3)

Vamsi Krishna
Vamsi Krishna

Reputation: 31362

One way of doing is to set up a meta field requiresDatePicker: true on the routes you want to show the datepicker

const router = new VueRouter({
  routes: [
    {
      path: "/foo",
      component: Foo,
      meta: { requiresDatePicker: true }
    },
    {
      path: "/bar",
      component: Bar,
      meta: { requiresDatePicker: false }
    }
  ]
});

Then use the meta property on the route object to check if the particular route has to render the datepicker or not

<main>
  <date-picker v-if="$route.meta.requiresDatePicker"></date-picker>
  <router-view></router-view>
</main> 

credits to @Konrad K for mentioning out in the comments

Upvotes: 6

Imre_G
Imre_G

Reputation: 2535

The easiest way is to use window.location.href and check for your route there. Then add a v-if on your component. Something like this:

<main>
  <date-picker v-if = "enableDatePicker"></date-picker>
  <router-view></router-view>
</main>

<script>
export default {
    computed: {
        enableDatePicker: {
              return (window.location.href === myroute)
         }
    }
}
</script>

Upvotes: 0

Julian Paolo Dayag
Julian Paolo Dayag

Reputation: 3719

In your vuex, add a new state. Let's say, showDatePicker:

{
    state: {
        showDatePicker: false
    },
    mutation: {
        showDatePicker(state, show) {
            state.showDatePicker = show;
        }
    }
}

Then in your component, add a computed property for referencing the state:

import { mapState } from 'vuex'
...
computed: {
    ...mapState(['showDatePicker'])
}

then on the date-picker component add a condition:

 <date-picker v-if="showDatePicker"></date-picker>

then on the mounted callback on each page components, you can just toggle the value depending if you want to show the date picker or not:

mounted() {

    //show
    this.$store.commit('showDatePicker', true);

    //hide
    this.$store.commit('showDatePicker', false);

}

Upvotes: 1

Related Questions