LoginSignup
123
94

More than 5 years have passed since last update.

Vue.jsでコンポーネント作るときにCSS変数つかったら色々できる

Last updated at Posted at 2018-02-14

ブロック要素に内容を表示するだけの簡単なコンポーネントを作ったとします。
この要素幅や背景色を属性で指定したい場合、CSS変数を使うと以下のように実装できます。

Box.vue
<template>
  <div class="box" :style="styles"> <!-- computedなstylesプロパティをstyleにバインド-->
    <div class="message">
      <slot></slot>
    </div>
  </div>
</template>

<script>
export default {
  name: 'box',
  props: {
    color: {},
    width: {}
  },
  computed: {
    // バインドするスタイルを生成
    styles () {
      return {
        '--color': this.color,
        '--width': this.width
      }
    }
  }
}
</script>

<style scoped>

.box {
  /* デフォルトの値を宣言*/
  --color: orange;
  /* --width: width; */ /* 20180215 書き間違えていたため修正しました */
  --width: 100px;

  /* CSS変数を背景と幅に割り当て */
  background-color: var(--color);
  width: var(--width);

  display: inline-block;

}

.box .message {
  padding: 1em;
}
</style>

使うときはこんな感じになります。

App.vue
<template>
  <div id="app">
    <!-- 属性で色と幅をバインド -->
    <box class="green" :color="color" :width='width'>.green</box>

    <div>
      <!-- バインドした属性を編集する入力ボックス -->
      <input v-model='color'>
      <input v-model='width'>
    </div>
  </div>
</template>

<script>
export default {
  name: 'app',
  data () {
    // バインドする属性を宣言
    return {
      color: 'pink',
      width: '20px'
    }
  }
}
</script>

実行した様子は以下の感じです(画像なのでわかりにくいですが)。
入力ボックスに入力した値に応じてコンポーネントが変化します。

image.png

123
94
2

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
123
94