将类绑定到Vue.js 2中的插槽 [英] Bind class to a slot in Vue.js 2

查看:35
本文介绍了将类绑定到Vue.js 2中的插槽的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个可重复使用的组件,以遍历项目,对其进行过滤并向插槽添加一些类(如果项目是偶数,奇数,第一个,最后一个等).

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

这是我的可重用组件:

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

这是我的用法:

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

我做错什么了吗?在Vue.js 2中甚至在技术上可以做这样的事情吗?

Am I doing anything wrong? Is it even technically possible in Vue.js 2 to do something like this?

感谢您的帮助或建议!

推荐答案

具有 vuejs2 的插槽样式已被删除./migration.html#Slots"rel =" noreferrer>此处:

With vuejs2 styling from slots has been removed as stated here:

通过named插入的内容不再保留slot属性.使用包装元素为它们设置样式,或者在高级用例中,使用渲染功能以编程方式修改插入的内容.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆