我有一个菜单组件,简单地说,它带有一个带有一系列选项的道具,并在每个菜单的菜单中呈现一个项目.我希望能够根据用例自定义每个菜单项中的标记,因此我在菜单项元素中使用了占位符.
你可以在这个小提琴中看到一个这样的例子.
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');
Run Code Online (Sandbox Code Playgroud)
这在Vue.JS的v1上运行良好但在升级到v2之后我看到错误"重复存在插槽"默认"在同一渲染树中找到 - 这可能会导致渲染错误."
这是v2中可能出现的问题还是有另一种方法可以实现同样的目的?
cra*_*g_h 10
看起来你需要一个范围的插槽,所以你需要将你的slot内容包装在一个带有scope属性的模板中:
<custommenu>
<template scope="colour">
<span class="colour"></span>
</template>
</custommenu>
Run Code Online (Sandbox Code Playgroud)
然后,您需要将其添加到组件模板的插槽中:
<ul>
<li v-for="item in options" :class="item.colour">
<slot colour></slot>
<span class="label">{{item.name}}</span>
</li>
</ul>
Run Code Online (Sandbox Code Playgroud)
这是更新后的JSFiddle:https://jsfiddle.net/kLge4wun/