1
0

More than 1 year has passed since last update.

Vue.jsのv-bindを使ってclass属性を書き換える

Last updated at Posted at 2022-01-01

はじめに

v-bindについて学んでいきましょう。

v-bindとは

v-bindとは要素に含まれる属性を動的に設定・変更することが出来る設定方法です。

実際に例を見てみましょう

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

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
    <title>Document</title>
</head>

<body>
    <div id="app">
        <h1 v-bind:class="type">表示</h1>
        <!---------------------------------------------------
        ↑<h1 v-bind:class="type">表示</h1>の構文は、
        <h1 :class="type">表示</h1>⇦に省略も可能。
        ---------------------------------------------------->
    </div>
    <style>
        .error {
            color: red;
        }

        .success {
            color: aquamarine;
        }
    </style>
    <script>
        let app = new Vue({
            el: "#app",
            data: {
                type: "success"
            }
        });
    </script>
</body>

</html>

解説

初めに、el: "#app"でHTML内のid名appにアクセスしています。

次に、script内のdata: { type: "success" }と連携している部分を見ていきます。

・ dataの中のtypeはh1タグ内のv-bind:class="type"と連携しています。

・ dataの中のsuccessは、style内の.successと連携しています。

もっと細かく解説していくと、

data: { type: "success" }としていることで今回の場合、
styleタグ内ではで文字の色のみを指定しているので、
typeというクラスが当たっている文字の色はstyleの中の.successで指定されている色ですよ!ということを表しているのです。
もし、"success"の部分を"error"に変更した場合は、文字の色が赤色になります。
また、style内の.successや.errorのcssを色々いじってみると便利さが分かると思います。

おわり

ご覧いただきありがとうございました。

また別の記事でお会いしましょう〜👋

1
0
1

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