[Vuejs]-Is there a better way of dynamically adding classes in Vue than this?

2๐Ÿ‘

โœ…

I would prefer this.

<template>
    <div class="course-list">
        <div class="course-card" v-for="(course, index) in courses" :key="index" :class="'border-stage' + course.stage">
        <div class="card-header">Stage {{course.stage}}</div>
        <div class="card-body">
            <h5 class="card-title">{{course.title}}</h5>
            <p class="card-text">{{course.creator}}</p>
            <p class="card-text">{{course.hours}} Hours</p>
            <div class="add-btn" :class='bgClass[course.stage]'><i class="fas fa-plus fa-2x"></i></div>
            </div>
        </div>
    </div>
</template>
<script>
export default {
    data() {
        return {}
    }
}
</script>

<style lang="sass">
    // Stage borders
    .border-stage1 {
    border-top: 8px solid $red;
    border-right: 8px solid $red; 
    }

    .border-stage2 {
    border-top: 8px solid orange;
    border-right: 8px solid orange;
    }

    .border-stage3 {
    border-top: 8px solid orangered;
    border-right: 8px solid orangered;
    }

    .border-stage4 {
    border-top: 8px solid $green;
    border-right: 8px solid $green;
    }

    .border-stage5 {
    border-top: 8px solid $blue;
    border-right: 8px solid $blue;
    }

    .border-stage6 {
    border-top: 8px solid $teal;
    border-right: 8px solid $teal;
    }

    .border-stage7 {
    border-top: 8px solid $pink;
    border-right: 8px solid $pink;
    }

    .border-stage8 {
    border-top: 8px solid $info;
    border-right: 8px solid $info;
    }

    .border-stage9 {
    border-top: 8px solid #fff;
    border-right: 8px solid #ffff;
    }
</style>
๐Ÿ‘คmuya.dev

1๐Ÿ‘

You can use a template string if you use a v-bind like this:

<div class="course-card" :class="`border-stage${course.stage}`"

When using v-bind, the part between the quotes is just javascript.

๐Ÿ‘คSumurai8

Leave a comment