4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

qnoteAdvent Calendar 2023

Day 19

【Vue3.2】styleタグ内でv-bind

Last updated at Posted at 2023-12-18

はじめに

Styleタグ内でJSの変数とか書けないかなーと思ったら、ちょうどいいものがあったので備忘録がてら書きます。

環境

  • vue@3.2.41
  • TailwindCSS

やってみた

  • ref変数
hoge.vue
<template>
  <div class="p-10">
    <p class="text-blue font-bold text-xl">ほげほげ</p>
  </div>
</template>

<script setup>
import { ref } from "vue"

const textColor = ref('#0000ff')
</script>

<style scoped>
.text-blue {
  color: v-bind(textColor)
}
</style>

スクリーンショット 2023-12-19 1.15.21.png


  • 関数呼び出し
hoge.vue
<template>
  <div class="p-10">
    <p class="text-green font-bold text-xl">ほげほげ</p>
  </div>
</template>

<script setup>
import { ref } from "vue"

const textColor = () => '#48bb78'
</script>

<style scoped>
.text-green {
  color: v-bind(textColor())
}
</style>

スクリーンショット 2023-12-19 1.14.48.png


  • Styleタグ内でJavaScriptの式を記述

JavaScript式を展開するためには、
v-bindの引数をシングル(ダブル)クォーテーションで囲ってください。

hoge.vue
<template>
  <div class="flex items-center">
    <p class="text-line p-10 font-bold text-5xl">ほげほげ</p>
    <button
      class="bg-gray-300 h-10 w-1/5 border-2 border-black"
      @click="isUnderLine = !isUnderLine">
      ボタン
    </button>
  </div>
</template>

<script setup>
import { ref } from "vue"

const isUnderLine = ref(true)
</script>

<style scoped>
.text-line {
  text-decoration: v-bind('isUnderLine ? "underline" : "overline"');
}
</style>

タイトルなし.gif


  • 時間経過によるStyleの変化
hoge.vue
<template>
  <div class="bgc">
    change background-color
  </div>
</template>

<script setup>
import { ref } from "vue"

const bgStyle = ref('#ed8936')
setTimeout(() => {
  bgStyle.value = '#7f9cf5'
}, 3000)

</script>

<style scoped>
.bgc {
  background-color: v-bind(bgStyle);
}
</style>

タイトル動画.gif

まとめ

意外と便利。
Styleタグ内で複雑なJavaScriptは書けないが、簡単な変数・式展開であれば可能でした。

参考

4
0
0

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
4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?