Vue.js 基礎編④(watch・mounted)
■Vue.jsの基本的な文法(watch・mounted)について解説する
「v-bind(クラスの追加)」や「computed(算出プロパティ)」はこちら→Vue.js 基礎編③(「v-bind」・「computed」)
・「watch」を使用してデータをブラウザのローカルストレージに保存し、「mounted」でデータ呼び出し
【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>
<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: []
},
//「watch」で「items」配下のオブジェクトも含み、変化があった際にローカルストレージに保存
watch: {
items: {
handler: function(){
//ローカルストレージに「items」というキーで保存(JSON形式)
localStorage.setItem('items', JSON.stringify(this.items));
},
deep: true
}
},
//「mounted」でローカルストレージに保存したデータを読み出し
//呼び出しが失敗した際に備えて、空の配列を用意する
mounted: function(){
this.items = JSON.parse(localStorage.getItem('items')) || [];
},
methods: {
addItem: function(){
this.items.push(this.newItem);
this.newItem = '';
}
},
computed: {
countItem: function(){
return this.items.length;
}
}
});
})();