hidar
hidar

Reputation: 5949

How to apply more than one conditional style to elements

I have a div that looks like this

<div v-for="person in people">
    <p class='name' :class="{people.age == "adult" : 'green'}"></p>
</div>

I can change the class like that, but I have many age groups (around 8) and I am not sure how this can be done, without putting 8 logical arguments inside the element

Upvotes: 0

Views: 322

Answers (2)

user8573445
user8573445

Reputation:

It's bad practice to have a class called green - what happens one day when you redesign the site and suddenly what was once green is now blue.. you would have to go back and change the names of all the classes in the templates, and then go and change all the CSS as well.

It's much better practice to have a class called adult, and then actually set the color of adult in the CSS to "green".

Further to that, you should put the logic determining what group they fall into on the person model. So that you can simply call person.age_group (for example) and that would return the string adult which would then be mapped to whatever color you want).

That way, not only do you not have a big conditional block in your template, your other bits of code can call the same function and determine the "type" of user (adult/child etc)

Upvotes: 2

talkhabi
talkhabi

Reputation: 2759

Use a computed property like this:

computed: {
    computedPeople: function(){
        return this.people.map(function(person){
            person.cls = {
                green: person.age == "adult",
                //otherClass: otherCondition ...
                //...
                //...
            };
        });
    }
},

then

<div v-for="person in computedPeople">
    <p class='name' :class="person.cls"></p>
</div>

Upvotes: 1

Related Questions