[Vuejs]-Disable a component in a specific case in Vue.js

6πŸ‘

βœ…

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

πŸ‘€Vamsi Krishna

1πŸ‘

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

}

0πŸ‘

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>
πŸ‘€Imre_G

Leave a comment