LoginSignup
0
0

More than 1 year has passed since last update.

Vue3でpropsの値をCSSに渡す際に注意したいこと

Posted at

はじめに

久々に実装した際に、エラーも出力されず苦戦したので共有します。

サンプルコード

Sample.vue
<template>
  <span class="test" :style="styles">
    テスト
  </span>
</template>
<script lang="ts">
import { defineComponent, computed } from 'vue';

export default defineComponent({
  props: {
    color: { type: String, default: '#FFF' },
  },

  setup: (props) => {
    const styles = computed(() => ({
      '--color': props.color,
    }));

    return { styles };
  },
});
</script>

<style scoped>
.test {
  color: var(--icon-color);
}
</style>

ここで大事なのが、propsを渡すクラスをつけている要素のstyleフィールドに対して、stylesをbindしている箇所です。

Sample.vue
<span class="test" :style="styles">

これを忘れてしまうと、CSS内のvar変数に値が入らないので注意してください。

所感

自分の記憶や過去の自分のコードを信じるではなく、おかしいなと思ったら公式サイトをすぐに見に行ったほうが良いですね。

参考文献

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