Vue.js クラスのバインディングのサンプルコード

vue.jsでhtmlのクラスを動的に変更するサンプルコードです
環境
- OS Windos10
- エディタ VScode
基本構文
1 |
<p v-bind:class="{ active: show }">Hello World!</p> |
active と記載された箇所がクラス名
show と記載された箇所が true / false( 真偽値 )となります
true であれば activeクラスが有効になり、falseであれば無効になります。
サンプルコード
下記のソースコードをindex.htmlとして作成して保存します
vue.jsは下記の開発バージョンのものを利用してます <script src=”https://cdn.jsdelivr.net/npm/vue/dist/vue.js”></script>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
<!DOCTYPE html> <html> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title></title> <meta charset="utf-8"> <meta name="description" content=""> <meta name="author" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <style> .style1 { font-family: 'Avenir', Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 120px; } h3 { margin: 40px 0 0; color: #41B883; } .button { display: block; position: relative; margin: 0 auto; width: 140pt; border: solid 1px silver; border-radius: 0.5rem 0.5rem; padding: 0.5rem 1.5rem; margin-top: 1rem; text-decoration: none; } /*バインディングするクラス*/ .active { color: #DD3248; background: #DDD; } </style> <body> <div id="app" class="style1"> <h3>クラスのバインディング</h3> <button class="button" v-on:click="show=!show">クラスを有効にする</button> <p v-bind:class="{ active: show }">Hello World!</p> </div> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script> var app = new Vue({ el: '#app', data: { show: false } }) </script> </body> </html> |
保存したファイルをブラウザで開いて確認 。

「クラスを有効にする」ボタンをクリックすると、activeクラスが有効になり、記述した.activeのCSSが適応されます

-
前の記事
Ubuntu19.10にgo言語をインストール 2019.11.23
-
次の記事
手書き風のチャートが作成できるjavascriptライブラリ「roughViz.js」を利用してみる 2019.11.25
コメントを書く