Thomas Miller
Thomas Miller

Reputation: 115

Vue: add multiple classes inside a v-for, based on array

I need to add classes to an element, based on categories. Here is my example data:

data() {
  return {
    projects: [
      {
        title: 'Project 1',
        categories: [{ name: 'featured' }, { name: 'category-1' }],
      },
      {
        title: 'Project 2',
        categories: [{ name: 'category-2' }],
      },
    ],
  };
},

What I need is to add the categories directly as classes on the wrapper div (with the v-for), that will render:

<div class="featured category-1">
  <h3>Project 1</h3>
</div>
<div class="category-2">
  <h3>Project 1</h3>
</div>

I'm not sure how to do this?

<div v-for="(project, index) in projects" :class="v-for="(category, index) in project.categories???">
  {{project.title}}
</div>

Should I do this differently? I can't seem to figure it out. Thanks for your help!

Upvotes: 1

Views: 725

Answers (1)

dziraf
dziraf

Reputation: 3653

It's simple:

  <div v-for="project in projects" :class="classExtraction(project)">
    <h3>
    {{project.title}}
    </h3>
  </div>

You need a method that extracts classes from your project's categories:

  methods: {
    classExtraction(item) {
        return item.categories.map(cat => cat.name);
    }
  }

http://jsfiddle.net/eywraw8t/371192/

Also, please note that you should use :key directive with v-for binding it to a unique property, preferably object's id: https://v2.vuejs.org/v2/style-guide/#Keyed-v-for-essential

Upvotes: 5

Related Questions