Search code examples
javascriptvue.jsvue-component

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>

Solution

  • 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