将类绑定到 Vue.js 2 中的插槽 [英] Bind class to a slot in Vue.js 2
问题描述
我正在尝试创建一个可重复使用的组件,用于迭代项目、过滤它们并将一些类添加到槽中(如果项目是偶数、奇数、第一个、最后一个等.)
这是我的可重用组件:
<ul :class="classes"><插槽v-for="(item, index) in filtersItems":项目=项目":class="{'第一个':索引== 0,'奇': !(索引 % 2),偶数":索引 % 2,'last': index == (filteredItems.length - 1)}"></slot>模板><脚本>导出默认{道具:['物品','类'],数据() {返回 {过滤项目:this.items.filter(item => item.active)};}};
这是我如何使用它:
<模板范围=道具"><product :product="props.item"></product>模板><组件列表>
一切都按预期工作,但它没有向放置在里面的元素添加类.
我做错了什么吗?在 Vue.js 2 中甚至在技术上有可能做这样的事情吗?
感谢您的任何帮助或建议!
With vuejs2
样式从插槽中删除,如所述 此处:
通过命名插入的内容不再保留插槽属性.使用包装元素为其设置样式,或者对于高级用例,使用渲染函数以编程方式修改插入的内容.
建议的最简单的事情是使用包装元素,如下所示:
<ul :class="classes"><插槽></slot>模板>
I'm trying to create a reusable component for iterating over items, filtering them, and adding some classes to the slot (if the item is even, odd, first, last etc..)
Here's my reusable component:
<template>
<ul :class="classes">
<slot
v-for="(item, index) in filteredItems"
:item="item"
:class="{
'first': index == 0,
'odd': !(index % 2),
'even': index % 2,
'last': index == (filteredItems.length - 1)
}"
>
</slot>
</ul>
</template>
<script>
export default {
props: ['items', 'classes'],
data() {
return {
filteredItems: this.items.filter(item => item.active)
};
}
};
</script>
And here's how I use it:
<component-list :classes="'some-class'" :items="category.products">
<template scope="props">
<product :product="props.item"></product>
</template>
<component-list>
Everything works as expected, but it doesn't add classes to the element put inside .
Am I doing anything wrong? Is it even technically possible in Vue.js 2 to do something like this?
Thanks for any help or suggestion!
With vuejs2
styling from slots has been removed as stated here:
Content inserted via named no longer preserves the slot attribute. Use a wrapper element to style them, or for advanced use cases, modify the inserted content programmatically using render functions.
So simplest thing as suggested will be to use a wrapper element as following:
<template>
<ul :class="classes">
<slot>
<div
v-for="(item, index) in filteredItems"
:item="item"
:class="{
'first': index == 0,
'odd': !(index % 2),
'even': index % 2,
'last': index == (filteredItems.length - 1)
}"
>
</div>
</slot>
</ul>
</template>
这篇关于将类绑定到 Vue.js 2 中的插槽的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!