1

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>
4
  • please share the code of parent component Commented Sep 26, 2020 at 15:57
  • 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. Commented Sep 26, 2020 at 15:57
  • @BoussadjraBrahim I added some code Commented Sep 26, 2020 at 16:00
  • menu: [ 'Item': { href: '#' } ] is not a valid syntax you should do menu: [{ href: '#' } ] Commented Sep 26, 2020 at 16:07

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.