1. 基本的なクラスバインディング
通常のCSSクラスを直接要素に適用する方法です。
<template>
<div class="blue-box">
Vue.jsの世界へようこそ
</div>
</template>
<script>
export default {
}
</script>
<style lang="scss" scoped>
.blue-box {
width: 150px;
height: 80px;
background-color: #3498db;
display: flex;
align-items: center;
justify-content: center;
border-radius: 8px;
}
</style>
2. 動的なクラスバインディング
データプロパティを利用して動的にクラスをバインドします。
<template>
<div :class="dynamicClass">
動的なスタイル適用中
</div>
</template>
<script>
export default {
data() {
return {
dynamicClass: "blue-box"
}
}
}
</script>
<style lang="scss" scoped>
.blue-box {
width: 200px;
height: 100px;
background: #2ecc71;
border-radius: 12px;
display: flex;
align-items: center;
justify-content: center;
}
</style>
3. 複数クラスの動的バインディング
条件に応じて複数のクラスを適用します。
<template>
<div :class="{'highlight': showHighlight, 'blue-box': showBox}">
複数クラスの適用例
</div>
</template>
<script>
export default {
data() {
return {
showHighlight: true,
showBox: true
}
}
}
</script>
<style lang="scss" scoped>
.highlight {
font-weight: bold;
color: #e74c3c;
font-size: 18px;
}
.blue-box {
padding: 20px;
background-color: #3498db;
border-radius: 8px;
margin: 10px;
}
</style>
4. 静的クラスと動的クラスの組み合わせ
通常のクラス宣言と動的クラスバインディングを組み合わせて使用できます。
<template>
<div class="blue-box" :class="{'highlight': showHighlight}">
組み合わせたクラス適用
</div>
</template>
5. 配列形式でのクラスバインディング
配列形式で複数のクラスをバインドします。
<template>
<div :class="[class1, class2]">
配列形式でのクラス適用
</div>
</template>
<script>
export default {
data() {
return {
class1: "blue-box",
class2: "highlight"
}
}
}
</script>
<style lang="scss" scoped>
.blue-box {
width: 250px;
height: 120px;
background: #9b59b6;
border-radius: 10px;
display: flex;
align-items: center;
justify-content: center;
}
.highlight {
color: white;
font-weight: bold;
}
</style>
6. 三項演算子を使った条件付きクラス
三項演算子を利用して条件に応じたクラスを選択します。
<div :class="[isActive ? 'active-class' : 'inactive-class']">
条件付きクラスの適用
</div>
7. 配列とオブジェクトの組み合わせ
配列とオブジェクトを組み合わせてより柔軟なクラス制御が可能です。
<div :class="[{ 'active-class': isActive }, 'base-class']">
配列とオブジェクトの組み合わせ
</div>
8. v-bind:styleを使ったインラインスタイルバインディング
JavaScriptオブジェクトを直接スタイルにバインドします。
オブジェクト構文
<!-- 基本的なオブジェクト構文 -->
<div :style="{ color: textColor, 'font-size': fontSize + 'px', backgroundColor: bgColor }">
インラインスタイルの適用
</div>
<!-- データプロパティからの値 -->
<div :style="styleObject">
プロパティからのスタイル適用
</div>
<script>
export default {
data() {
return {
textColor: '#2c3e50',
fontSize: 16,
bgColor: '#ecf0f1',
styleObject: {
color: '#e74c3c',
'font-family': "'Arial', sans-serif",
'border-radius': '5px',
padding: '10px'
}
}
}
}
</script>
配列構文
複数のスタイルオブジェクトを配列として適用できます。
<div :style="[baseStyle, overrideStyle]">
複数スタイルオブジェクトの適用
</div>
<script>
export default {
data() {
return {
baseStyle: {
color: '#2c3e50',
fontSize: '14px'
},
overrideStyle: {
'font-weight': 'bold',
'border': '1px solid #ddd'
}
}
}
}
</script>
注意点
- キャメルケース(fontSize)またはケバブケース('font-size')のどちらでもスタイル名を指定できます
- ケバブケースの場合は文字列として引用符で囲む必要があります
- 動的値をバインドする際は変数名をそのまま使用し、固定値は文字列で指定します