Vue.js watchを使用してデータを監視するサンプルコード

vueのwatch機能を利用して、指定したデータとオブジェクト(今回は配列)を監視し処理を実行する基本的なサンプルコードになります。
環境
- OS windows10 pro
- エディタ VScode
サンプルコード
下記のソースコードをindex.htmlとして作成して保存する。
vue.jsは開発バージョンを利用してます
<script src=”https://cdn.jsdelivr.net/npm/vue/dist/vue.js”></script>
<!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;
}
h4 {
margin: 40px 0 0;
color: #35495E;
}
.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;
}
/*[v-cloak] {display: none;} によりバインディングされるまでは非表示となる*/
[v-cloak] {
display: none;
}
</style>
<body>
<div id="app" class="style1">
<h3>flgを監視</h3>
<p>{{flg}}</p>
<button class="button" @click="changeFlg">フラグ変更</button>
<p>フラグ変更後 : {{newFlg}}</p>
<p>フラグ変更前 : {{oldFlg}}</p>
<h3>オブジェクトを監視</h3>
<input type="text" v-model="hogeArr[0]">
<input type="text" v-model="hogeArr[1]">
<input type="text" v-model="hogeArr[2]">
<p>変更後オブジェクト : {{arr}}</p>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
new Vue({
el: '#app',
data: {
flg: true,
newflg: '',
oldflg: '',
arr: '',
hogeArr: [
'変更',
'して',
'みる'
]
},
methods: {
changeFlg: function () {
this.flg = !this.flg
}
},
//監視するデータ: function(新しい値, 古い値)
watch: {
flg: function (newFlg, oldFlg) {
// watchが変化した際に実行される処理
this.newFlg = newFlg
this.oldFlg = oldFlg
//オブジェクトの監視はhandlerプロパティとdeep: trueを利用する
},hogeArr: {
handler: function(newVal, oldVal){
this.arr = newVal
},
deep: true
}
}
});
</script>
</body>
</html>
保存したファイルをブラウザで開いて確認。

「フラグを変更」ボタンをクリックすると変更前と変更後のフラグが表示される

オブジェクトを変更すると、変更後の値が確認できます。

-
前の記事
Laravel6でvue.jsを利用する 2019.11.14
-
次の記事
Ubuntu19.10にsvelteをインストールして利用してみる 2019.11.16
コメントを書く