添加 <slot>在重复内容区域

编程入门 行业动态 更新时间:2024-10-09 21:26:11
本文介绍了添加 <slot>在重复内容区域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我有一个菜单组件,简单地说,它接收一个带有一系列选项的道具,并在菜单中为每个选项呈现一个项目.我希望能够根据用例自定义每个菜单项内的标记,因此我在菜单项元素内使用了占位符.

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.

您可以在此 fiddle 中看到一个示例.

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');

这在 Vue.JS 的 v1 上运行良好,但升级到 v2 后,我看到错误在同一渲染树中发现插槽默认"重复存在 - 这可能会导致渲染错误.

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. "

这在 v2 中是可能的,还是有其他方法可以实现相同的目标?

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

推荐答案

看起来你需要一个 scoped slot 用于此,因此您需要将 slot 内容包装在具有 scope 属性的模板中:

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>

这是更新后的 JSFiddle:https://jsfiddle/kLge4wun/

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

这篇关于添加 <slot>在重复内容区域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-27 01:10:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1145652.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:区域   内容   lt   slot   gt

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!