0

I'm trying to set a dynamic class in a vue.js, something like

 <strong :class=`color-${category.level}`>{{ category.name }}</strong>

this html is inside a for loop and I need the category.value on this loop but it's not working

2 Answers 2

1

The bound class value should be wrapped by quotes :class='...' or double-quotes :class="..." :

<strong :class="`color-${category.level}`"></strong>
Sign up to request clarification or add additional context in comments.

Comments

0

Add function in :class in your case

 :class="switchClass(category.level)"

and then in methods

 switchClass(level) {
    return `color-${level}`
  }

4 Comments

This will probably work, but imo this is a bit "too much" for this. I would probably use this approach if there were a few conditions involved
This will work as i am using this approach and yes for multiple conditions.
Yes, sure! And if it gets the job done, go ahead and use it. What I am trying to say is that The answer above might be preferred because it doesn't have the overhead cost of an extra method in your component. That space is valuable, imagine having 12 of these in a component. It will make it harder to reason about.
And in terms of semantics, a class name does belong to your template part, it is determining how it should look like, not how it's rendered or what is rendered. Therefore I could agree that this "easy" logic or concatenating is more at home inside the template. But again, you should just do it the way it works for you and your team, I am talking from a more general point of view

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.