Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hiding Element Based on Route Path or Params in Vue

Tags:

vue.js

I'm trying to hide the main app navigation bar based on if the route is on a given path.

In my App.vue component, in the created() method. I do check to see if the route is x || y, if either of those are true, I set my Vuex state of show to false. If it is any other route besides those two, I set show = true.

Then in my template I do this

<template>
    <div id="app">
      <navigation v-show="show"></navigation>
      <router-view></router-view>
    </div>
</template>

I'm noticing in Vuex tools that my mutations aren't even registering so I'm not sure why that is. Do they need to be actions instead? Here is my full code.

<template>
    <div id="app">
      <navigation v-show="show"></navigation>
      <router-view></router-view>
    </div>
</template>

<script>
import Navigation from './components/Navigation/Navigation'
import { firebaseAuth } from './firebase/constants'
import store from './store/index'

export default {
  name: 'app',
  components: {
    Navigation
  },
  computed: {
    show () {
        return store.state.navigation.show
    }
  },
  created() {

    // Checks for a user and dispatches an action changing isAuthed state to true. 

    firebaseAuth.onAuthStateChanged(user => {
      console.log(store.state.authentication);
      console.log(user);
      store.dispatch('checkUser', user);
    }); 

    // Check if given route is true, if it is then hide Nav. 

    if (this.$route.path === "/dashboard/products" || this.$route.path === "/dashboard/settings") {
        store.commit('hideNav');
        } else if (this.$route.path !== "/dashboard/products" || this.$route.path !== "/dashboard/settings") {
        store.commit('showNav');
    }

  }
};

</script>
like image 792
maxwellgover Avatar asked Jan 06 '17 19:01

maxwellgover


1 Answers

This may not be working as created is called only once after the instance is created. but when routes changes, it will not be called, so not triggering the mutations you are expecting to trigger on route change, instead of this, you can put a watch on route, so on each route change, you can check whether to show your Nav Bar or not, like following;

Working fiddle: http://jsfiddle.net/ofr8d85p/

watch: {
   $route: function() {
    // Check if given route is true, if it is then hide Nav. 
    if (this.$route.path === "/user/foo/posts") {
        store.commit('SHOWNAV');
        } else  {
        store.commit('HIDENAV');
    }
  }
},
like image 79
Saurabh Avatar answered Oct 20 '22 22:10

Saurabh