Bootstrap-vue - Modify Navbar from Vue component?

216 views Asked by At

I have a Vue Bootstrap SPA with the following structure:

  • layout
    • navbar
    • breadcrumb
    • router view
  • component
    • some content

I would like my component to inject a submenu to the parent's navbar. For example:

export default {
    name: 'Component',
    data() {
       return {
           menu: [
               'Item': {
                   href: '#'
               }
           ]
       }
    },
    mounted() {
       parent.menu.addItem(this.menu)
    }
}

Is this possible to do something like this?

Here the top layout:

<template>
  <div>
    <navbar :menu="menu"></navbar>
    <router-view></router-view>
  </div>
</template>

<script>
import NavBar from './navbar'

export default {
  components: {
    navbar: NavBar
  },
  data() {
    return {
      menu: [
        {
          text: "Foo",
          href: "/foo",
        },
        {
          text: "Bar",
          href: "#",
        },
      ],
    };
  },
};
</script>
1

There are 1 answers

0
Boussadjra Brahim On BEST ANSWER

You could emit an event to the parent component like :

    data() {
       return {
           menu: [
                 {
                   href: '#'
               }
           ]
       }
    },
    mounted() {
       this.$emit('emit-menu',this.menu)
    }

in parent :

<template>

<navbar :menu="menu" @emit-menu="addItem"></navbar> 

    <router-view></router-view>
  </div>
</template>

<script>
import NavBar from './navbar'

export default {
  components: {
    navbar: NavBar
  },
  methods:{
   addItem(menu){
       this.menu=[..this.menu,...menu]
  }
 },
  data() {
    return {
      menu: [
        {
          text: "Foo",
          href: "/foo",
        },
        {
          text: "Bar",
          href: "#",
        },
      ],
    };
  },
};
</script>