Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding <slot> in repeating content region

Tags:

vue.js

vuejs2

I have a menu component which, simplistically, takes in an prop with an array of options and renders an item in the menu for each one. I wanted to be able to customise the markup that was inside each of the menu items depending on the use-case so I used the placeholder inside the menu item element.

You can see an example of this in this fiddle.

const Menu = {
    template: `
        <ul>
            <li v-for="item in options" :class="item.colour">
            <slot></slot>
            <span class="label">{{item.name}}</span>
          </li>
        </ul>
    `,
    data: () => {
        return {
            options: [
                { name: 'one', colour: 'red' },
                { name: 'two', colour: 'green' },
                { name: 'three', colour: 'blue' },
                { name: 'four', colour: 'yellow' }
            ]
       };
    }
};


const app = new Vue({
    components: {
        custommenu: Menu,
      },
    template: `<custommenu><span class="colour"></span></custommenu>`
});

app.$mount('#app');

This worked fine on v1 of Vue.JS but after upgrading to v2 I'm seeing the error "Duplicate presence of slot "default" found in the same render tree - this will likely cause render errors. "

Is this something that is possible in v2 or is there an alternative way to achieve the same thing?

like image 353
Stuart Avatar asked Jan 25 '17 11:01

Stuart


1 Answers

It looks like you will need a scoped slot for this, so you will need to wrap your slot content in a template with a scope attribute:

<custommenu>
  <template scope="colour">
    <span class="colour"></span>
  </template>
</custommenu>

Then you will need to add that to the slot in your component template:

<ul>
  <li v-for="item in options" :class="item.colour">
    <slot colour></slot>
    <span class="label">{{item.name}}</span>
  </li>
</ul>

Here's the updated JSFiddle: https://jsfiddle.net/kLge4wun/

like image 85
craig_h Avatar answered Oct 15 '22 17:10

craig_h