jules
jules

Reputation: 437

How to add class from content of a variable in Vue.js

I want to pass a variable to a component which should be added as a class to a div. However, Vue adds the name of the variable instead of the content.

So I pass the prop color which contains red.
What I want: <div class="red">2</div>
What I get: <div class="color">2</div>

I think this is a noob question, so sorry for that. Maybe there is a better way to do this.

Thanks for helping me out.

Here are my components:

<template>
    <div class="btn btn-outline-primary cell"
         :class="{color}"
         :id="id">
        {{ number }}
    </div>
</template>

<script>
    export default {
        name: "TileElement",
        props: ["id", "number", "color"]
    }
</script>

<style scoped>
    .green {
        color: green;
    }

    .red {
        color: red;
    }

    .yellow {
        color: yellow;
    }

    .cell {
        display: inline-block;
        float: left;
        margin: 0.1em;
        text-align: center;
        background-color: lightgray;
        width: 2.7em;
        height: 2.7em;
    }
</style>

Parent Component:

<template>
    <div class="row">
        <TileElement
                v-for="tile in tiles"
                v-bind:key="tile.id"
                v-bind:number="tile.number"
                v-bind:color="tile.color"
        ></TileElement>
    </div>
</template>

<script>
    import TileElement from './TileElement.vue';

    export default {
        name: "TileRow",
        components: {
            TileElement
        },
        data: function () {
            return {
                tiles: [
                    {id: 1, number: 1, color: "green"},
                    {id: 2, number: 2, color: "red"},
                    {id: 3, number: 3, color: "yellos"}
                ]
            }
        }
    }
</script>

Upvotes: 8

Views: 30700

Answers (4)

chaggy
chaggy

Reputation: 1131

<div v-for="var in variable" :class="'class-'+var">{{ var }}</div>

this is a simple way to dynamically create a class dependent on the variable

Upvotes: 2

bonusrk
bonusrk

Reputation: 717

If you just need to pass a class, without any conditions or other such stuff, then you can simple use array for one and any other number of classes:

<div :class="[color]"></div>

But that's not only you can do.

https://v2.vuejs.org/v2/guide/class-and-style.html

Upvotes: 17

blex
blex

Reputation: 25634

:class="color" will also work:

var vm = new Vue({
  el: '#app',
  data() {
    return {
      color: 'red'
    };
  }
});
.cell { width: 50px; height: 50px; }
.red { background: red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.21/vue.min.js"></script>

<div id="app">
  <div class="cell" :class="color"></div>
</div>

Upvotes: 5

Justin Levine
Justin Levine

Reputation: 285

Try dynamically importing the class name

:class="{[color]: true}"

Upvotes: 4

Related Questions