CSS Modulesの色々な書き方について
単一のクラスを指定
scoped との違いは
classを:classに- クラス名の前に
$style.を付与 <style module>のようにmoduleを使う事を記載
<template>
<h2 :class="$style.title">タイトル</h2>
</template>
<style module>
.title {
font-size: 30px;
}
</style>
(参考)scopedで書いた場合
<template>
<h2 class="title">タイトル</h2>
</template>
<style scoped>
.title {
font-size: 30px;
}
</style>
複数のクラスを指定
配列で渡してあげればOK!
<template>
<h2 :class="[$style.title, $style.blue]">タイトル</h2>
</template>
<style module>
.title {
font-size: 30px;
}
.blue {
color: #00f;
}
</style>
条件に応じてそれぞれ別のクラスを付与
三項演算子を使用
isImportant の値に応じて $style.red と $style.blue がトグルします
<template>
<h2 :class="[$style.title, isImportant ? $style.red : $style.blue]">タイトル</h2>
</template>
<script>
export default {
data: () => ({
isImportant: true,
}),
}
</script>
<style module>
.title {
font-size: 30px;
}
.red {
color: #f00;
}
.blue {
color: #00f;
}
</style>isImportant が true の場合
isImportant が false の場合
特定条件の場合のみクラスを付与
いくつか方法があります
三項演算子を使う
まずさっきの方法と近いやり方
isCompleted が true の場合は null を渡す事でクラスが付与されません。
null を渡してしまうのが「うーん🤔」となるところ
<template>
<!-- 完成していない場合タイトルを赤くするようなイメージ -->
<h2 :class="[$style.title, !isCompleted ? $style.red : null]">タイトル</h2>
</template>
<script>
export default {
data: () => ({
isCompleted: false,
}),
}
</script>
<style module>
.title {
font-size: 30px;
}
.red {
color: #f00;
}
</style>オブジェクトを使う
少し難しめ。
オブジェクトのvalueが ture の場合、keyとなる値がクラスとして付与される特性を利用します。
公式のこの機能ですね
<div v-bind:class="{ active: isActive }"></div>
v-bind:classにオブジェクトを渡すことでクラスを動的に切り替えることができます 上記の構文は、activeクラスの有無がデータプロパティisActiveの真偽性によって決まることを意味しています。
またES6から実装されたオブジェクトのkeyに変数を使う方法を使います。
var myValue = "this_is_value"; var myKey = "this_is_key"; var obj = {[myKey]: myValue}; // => {"this_is_key": "this_is_value"}
<template>
<!-- 完成していない場合タイトルを赤くするようなイメージ -->
<h2 :class="[$style.title, { [$style.red]: !isCompleted }]">タイトル</h2>
</template>
<script>
export default {
data: () => ({
isCompleted: false,
}),
}
</script>
<style module>
.title {
font-size: 30px;
}
.red {
color: #f00;
}
</style>三項演算子でもオブジェクトを使っても結果は一緒
isCompleted が true の場合
isCompleted が false の場合