最終更新日 2025-04-18

クラスとスタイルのバインディング

概要

クラスとスタイルのバインディング

:class

オブジェクトで、プロパティを定義して、それぞれのキーを「true」か「false」にすると、
trueのものだけ、クラス名が適用される。

複数のクラスをまぜる

配列にすることで混ぜることが出来る。


<script setup>
import {reactive, ref} from 'vue'; // reactiveの代わりにrefを使用

const activeClass = ref('active')
const errorClass = ref('text-danger')
</script>
<template>
<div :class="[activeClass, errorClass]"></div>
</template>

:style

オブジェクトで、プロパティを定義すると、そのままキーと値がスタイルとして適用される。

複数のスタイルをまぜる

配列にすることで混ぜることが出来る。


<script setup>
import {reactive, ref} from 'vue'; // reactiveの代わりにrefを使用

const baseStyles = {
  width: '100px',
  height: '100px',
  backgroundColor: 'blue',
};
const overridingStyles = reactive({
  backgroundColor: 'red',
});
</script>
<template>
<div :style="[baseStyles, overridingStyles]"></div>
</template>