问题描述
限时送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:关键词]
发布评论