0
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 3 years have passed since last update.

Vue.jsで複数のclassをバイディングする方法

0
Last updated at Posted at 2022-01-13

はじめに

「Vue.jsで動的に見た目を変更するために、どうやって複数のクラスを適用したらいいのか?」と思い、v-bindディレクティブで、どうすれば複数のクラスをバイディングするのかその実装方法をまとめました。

バージョン
Vue.js 2.6.11

結論

複数のクラスを適用したい場合は、配列構文を使い、同じ要素に複数のスタイルオブジェクトをバインディングすることができます。

実装例

各項目に「色」「is-active」を付与する、簡単な例です。
スクリーンショット 2022-01-03 16.41.13.png

1. 配列構文

<template>
  <div id="app">
    <nav class="nav">
      <ul class="nav__list">
        <li
          class="nav__item"
          v-for="(nav, index) in navs"
          :key="index"
          :class="[
            nav.isActive ? 'is-active' : '',
            `nav__item--${nav.color}`,
          ]"
        >
          {{ nav.label }}
        </li>
      </ul>
    </nav>
  </div>
</template>

<script>
export default {
  name: "App",

  data() {
    return {
      navs: [
        {
          label: "ホーム",
          color: "black",
          isActive: true,
        },
        {
          label: "会社概要",
          color: "green",
          isActive: false,
        },
        {
          label: "事業紹介",
          color: "blue",
          isActive: false,
        },
        {
          label: "お問い合わせ",
          color: "orange",
          isActive: false,
        },
      ],
    };
  },
};
</script>

<style>
# app {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: #2c3e50;
  margin-top: 30px;
}

.nav__item {
  text-decoration: underline;
}
.nav__item.is-active {
  font-weight: bold;
  text-decoration: none;
}

.nav__item--black {
  color: black;
}
.nav__item--green {
  color: green;
}
.nav__item--blue {
  color: blue;
}
.nav__item--orange {
  color: orange;
}
</style>

2. リファクタリング

is-activeクラスの部分が、三項演算子式を使って少し冗長になってます。
配列構文の内部ではオブジェクト構文が使えるので、
オブジェクト構文でリファクタリングしてみます。

<template>
  <div id="app">
    <nav class="nav">
      <ul class="nav__list">
        <li
          class="nav__item"
          v-for="(nav, index) in navs"
          :key="index"
          :class="[{ 'is-active': nav.isActive }, `nav__item--${nav.color}`]"
        >
          {{ nav.label }}
        </li>
      </ul>
    </nav>
  </div>
</template>

最後に

リファクタリングを少しは見やすいコードになったと思います。

複数のクラスを適用したい場合は

  • 配列構文を使う
  • 配列構文の内部ではオブジェクト構文を使う

参考にどうぞ!

参考文献

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?