在VueJS 2中使用v作为第二个参数突出显示index和index+1



根据VueJS 2项目,我需要"高亮显示">数组的第一个和第二个元素(它们必须比其他元素大(,我使用v-for语法来迭代父组件的子组件。

搜索了一段时间后,我发现可以在v上调用第二个参数,例如v-for="(item, index)" of items,其中indexindex+1应该绑定为HTML类,以修改第一个和第二个的呈现。希望我足够清楚。。如果需要,可以随时问我。。我写了下面的代码,它几乎可以工作,但我仍然遇到了一个问题,因为我的卡实际上被重复了很多次(3次(。。有没有一种更优雅的方法可以在VueJS中完成这项工作?

父组件:

<template>
<div>
<child-card v-for="(item, index) of items" :item="item" :index="index">
</child-card>
</div>
</template>
<script>
export default {
name: 'parent-video-list',
components: {
ChildCard
},
props: {
items: {
type: Array,
required: true
}
}
};
</script>

子组件:

<template>
<main>
<a :href="item.link"></a>
<img :src="item.image.url" alt="">
<footer>
<h2>{{ item.title }}</h2>
<div class="author">{{ item.creator }}</div>
</footer>
</main>
<main v-if="index">
<a :href="item.link"></a>
<img :src="item.image.url" alt="">
<footer>
<h2>{{ item.title }}</h2>
<div class="author">{{ item.creator }}</div>
</footer>
</main>
<main v-if="index + 1" class="highligths2">
<a :href="item.link"></a>
<img :src="item.image.url" alt="">
<footer>
<h2>{{ item.title }}</h2>
<div class="author">{{ item.creator }}</div>
</footer>
</main>
</template>
<script>
export default {
name: 'childcard',
props: {
item: {
type: Object,
required: true
},
index: {
type: Number
// required: true
}
}
};
</script>

PS:其中子级中的第二个块具有不同的css类

由于您只想在某些索引处对项目进行样式设置,我建议您查看:

https://v2.vuejs.org/v2/guide/class-and-style.html

实现它可能看起来像这样:

<main v-bind:class="{ highlights1: index === 0, highlights2: index === 1 }">
...
</main>

或使用计算属性的clean,但我将把它留给您来实现。

最新更新