Vue.js v-bindでstyleを指定する

  • 作成日 2021.08.15
  • 更新日 2021.08.16
  • Vue.js
Vue.js v-bindでstyleを指定する

Vue.jsで、v-bindでstyleを指定するサンプルコードを記述してます。 「vue3」を使用してます。

環境

  • OS windows10 pro 64bit
  • Vue.js 3.2.2
  • Apache 2.4.43
  • ブラウザ chrome 92.0.4515.107

styleを指定

v-bindでstyleを指定するには、「v-bind:style」を使用します。
「v-bind:style」は、「:style」と省略できます。

以下は、変数に配列で用意したstyleを「div」タグにバインドさせるサンプルコードとなります。

※「vue3」は「cdn版」、デザインは「semantic-ui」を使用してます。

<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <!-- semantic.css  -->
  <link rel="stylesheet" type="text/css"
    href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css">
  <script src="https://unpkg.com/vue@next"></script>

</head>
<style>
  body>.grid {
    height: 100%;
  }
</style>

<body>
  <div id="app" class="ui middle aligned center aligned grid">

    <div class="column">

      <div :style="{ color: hoge, fontSize: foo }">elm</div>

    </div>

  </div>
  <script>

    const hoge = {
      data() {
        return {
          hoge: "#3DB70E",
          foo: "50px",
        }
      }
    }

    Vue.createApp(hoge).mount('#app')

  </script>
</body>

</html>

styleが設定されていることが確認できます。

オブジェクトの配列で指定することも可能です。

<div :style="[{ color: hoge }, { fontSize: foo }]">elm</div>

オブジェクトをそのまま使用することも可能です。

<div :style="obj">elm</div>

data() {
  return {
    obj: {
      color: "#3DB70E",
      fontSize: "50px"
    }
  }
}s