0
votes

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
please share the code of parent componentBoussadjra Brahim
While it might work, you could try using $emit, with or without an event bus to notify that the parent element should insert the sub-menu.Heri Hehe Setiawan
@BoussadjraBrahim I added some codenowox
menu: [ 'Item': { href: '#' } ] is not a valid syntax you should do menu: [{ href: '#' } ]Boussadjra Brahim

1 Answers

1
votes

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>