我需要根据类别向元素添加类。这是我的示例数据:
data() {
return {
projects: [
{
title: 'Project 1',
categories: [{ name: 'featured' }, { name: 'category-1' }],
},
{
title: 'Project 2',
categories: [{ name: 'category-2' }],
},
],
};
},
我需要的是将类别直接添加为包装div上的类(带有v-for),这将呈现:
<div class="featured category-1">
<h3>Project 1</h3>
</div>
<div class="category-2">
<h3>Project 1</h3>
</div>
我不确定该怎么做?
<div v-for="(project, index) in projects" :class="v-for="(category, index) in project.categories???">
{{project.title}}
</div>
我该怎么做?我似乎无法弄清楚。感谢您的帮助!
答案 0 :(得分:4)
很简单:
<div v-for="project in projects" :class="classExtraction(project)">
<h3>
{{project.title}}
</h3>
</div>
您需要一种从项目类别中提取类的方法:
methods: {
classExtraction(item) {
return item.categories.map(cat => cat.name);
}
}
http://jsfiddle.net/eywraw8t/371192/
此外,请注意,您应该将:key
伪指令与v-for
结合使用,以将其绑定到唯一属性,最好是对象的id
:
https://vuejs.org/v2/style-guide/#Keyed-v-for-essential