LoginSignup
9

More than 5 years have passed since last update.

Vue.jsで条件によって:classの値を変える

Posted at

Aだったら赤文字、Bだったら黒文字にしたい、みたいな要件の時に、条件によって要素に適用するclassを変えたい時ありますよね。
以下のようにmethods内で場合分けして、結果をテンプレートの:classに適用することで、テンプレート内にロジックを書かずに済みます。
※引数が無い場合はmethodsでなくcomputedでOK

<template>
    <ul>
        <li v-for="loop in loops" :class="fontColor(loop)"></li>
    </ul>
</template>
<script>
export default {
    data: function () {
        return {
            classGrey: '-grey',
            classRed: '-red',
            loops: [1,2,3,4,5]
        }
    },
    methods: {
        fontColor: function(loop) {
            if (loop === 1) {
                return this.classRed;
            } else {
                return this.classGrey;
            }
        }
    }
}
</script>

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9