Vue.js 基礎編③(v-bind・computed)
■Vue.jsの基本的な文法(v-bind・computed)について解説する
ループ処理やイベント処理はこちら→Vue.js 基礎編②(v-for・v-on・methods)
・「v-bind」ディレクティブでクラス属性を追加する
【HTMLファイル】
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css">
<title>Vue.js</title>
</head>
<body>
<div id="result">
<h1>Vue.jsの文法</h1>
<ul>
<li v-for="item in items">
<!-- Vue.jsで設定した「item.isBoolean」が「ture」だったら「change_color」クラス要素を追加 -->
<!-- 「change_red」クラスは文字色を赤色にするスタイルにする -->
<!-- <span v-bind:class="{change_red: item.isBoolean}">{{ item.title }}</span> -->
<!-- 「v-bind」は省略可能 -->
<span :class="{change_red: item.isBoolean}">{{ item.title }}</span>
</li>
</ul>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="main.js">
</script>
</body>
</html>
【JavaScriptファイル】
(function() {
'use strict';
let vm = new Vue({
el: '#result',
data: {
items: [{
//赤文字で出力
title: 'item_1',
isBoolean: true
}, {
//黒文字で出力
title: 'item_2',
isBoolean: false
}, {
//赤文字で出力
title: 'item_3',
isBoolean: true
}]
}
});
})();
【cssファイル】
.change_red {
color:red;
}
・算出プロパティ「computed」で動的に追加したitem数を計算
【HTMLファイル】
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css">
<title>Vue.js</title>
</head>
<body>
<div id="result">
<h1>Vue.jsの文法</h1>
<!-- 追加したitem数を「computed」動的に出力 -->
<p>item数:{{ countItem }}</p>
<form @submit.prevent="addItem">
<input type="text" v-model="newItem">
<input type="submit" value="追加">
</form>
<ul>
<li v-for="item in items">
{{ item }}
</li>
</ul>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="main.js">
</script>
</body>
</html>
【JavaScriptファイル】
(function() {
'use strict';
let vm = new Vue({
el: '#result',
data: {
newItem: '',
items: []
},
methods: {
addItem: function(){
this.items.push(this.newItem);
this.newItem = '';
}
},
//算出プロパティ「computed」で動的に追加したitem数を計算
computed: {
countItem: function(){
//item数を「countItem」にセット
return this.items.length;
}
}
});
})();
算出結果
次はローカルストレージへのデータ保存について解説する→Vue.js 基礎編④(watch・mounted)