1

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!

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! Works great. Thanks a lot for your help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.