Vue-router: hide components in page change

Asked

Viewed 559 times

0

I am learning vuejs and now I came across a difficulty in hiding components when show the other routes for example:

<template>
  <div id="app">
     <ion-icon name="help-circle-outline" class="help"></ion-icon>
     <menuv></menuv><!-- componente a ser escondido quando a rota for carregada -->
     <router-view></router-view>
  </div>
</template>

How do I hide a component once the route is loaded?

  • Face it involves a much larger context than this code you have put here. Basically you will have to put a v-if in the menu tag validating according to the route.

  • ~Utilize vuex~

1 answer

0


You can create a plugin to store some settings:

./Components/config/index.js

import Vue from 'vue'
const globalConfig = new Vue({
    data: {
        menu: {
            show: true,
            hide_from_pages: [ 'Contact' ]
        }
    },
    methods: {
        show_or_hide: function(page) {
            this.menu.show = this.menu.hide_from_pages.includes(page) ? false : true;
        }
    }
});
globalConfig.install = () => {
    Object.defineProperty(Vue.prototype, 'globalConfig', {
        get () { return globalConfig }
    });
};

export default globalConfig

Import into the file main.js

...
import globalConfig from './config'
...

Vue.use(globalConfig);

Add the function scrollBehavior at your time VueRouter calling the method show_menu, pass as parameter the name of the loaded page.

new Router({
    routes: [
        { path: '/', name: 'Home', component: Home },
        { path: '/about', name: 'About', component: About },
        { path: '/contact', name: 'Contact', component: Contact },
    ],
    scrollBehavior (to, from, savedPosition) {
        globalConfig.show_menu(to.name)
    }
})

Use the directive v-show in the component:

<menuv v-show="globalConfig.menu.show"></menuv>

References

Browser other questions tagged

You are not signed in. Login or sign up in order to post.