はじめに
今回はVue.jsでバインドする方法を学んでいく。
テキストにバインドする
HTMLのテキスト部分にマスタッシュで{ { プロパティ名 } } を記述すると、アプリケーションのdataオプションに定義したプロパティの値が、その場所に置き換わり出力される。
hello.html
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>速習Vue.js</title> </head> <body> <div id="app"> {{ message}} </div> </body> <script src="https://cdn.jsdelivr.net/npm/vue@2.6.11"></script> <script src="./hello.js"></script> </html>
hello.js
var app = new Vue({ el: '#app', data: { message: 'こんにちは' } });
式を使った出力
hello.html
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>速習Vue.js</title> </head> <body> <div id="app"> {{ lang == 'ja' ? message_ja : message_en}} </div> </body> <script src="https://cdn.jsdelivr.net/npm/vue@2.6.11"></script> <script src="./hello.js"></script> </html>
hello.js
var app = new Vue({ el: '#app', data: { message_en: 'Hello', message_ja: 'こんにちは', lang: 'en' } });
var app = new Vue({ el: '#app', data: { message: 'こんにちは', } });
属性にバインドする
属性にバインドするには、バインドしたいデータプロパティ名を属性の値に記述し、属性名の前に「v-bind」を付ける。
hello.html
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>速習Vue.js</title> </head> <body> <div id="app"> <input type="text" v-bind:value="message"> </div> </body> <script src="https://cdn.jsdelivr.net/npm/vue@2.6.11"></script> <script src="./hello.js"></script> </html>
hello.js
var app = new Vue({ el: '#app', data: { message: 'こんにちは', } });
リストデータをバインドする
JavaScriptの入れるを使って表し、v-forを使うと、要素に配列データをバインドできる。
hello.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>速習Vue.js</title>
</head>
<div id='app'>
<table border="1">
<tr><th>商品コード</th><th>商品名</th></tr>
<tr v-for="item in products">
<td>{{item.code}}</td><td>{{item.name}}</td>
</tr>
</table>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.11"></script>
<script src="./hello.js"></script>
</html>
hello.js
コメント