Vue.js watch example

by ChangJoo Park

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <div id="app">
        <label>km: <input type="text" v-model="km2"></label><br/>
        <label>cm: <input type="text" v-model="cm"></label><br/>
        <label>mm: <input type="text" v-model="mm"></label><br/>
    </div>
</body>
</html>

CSS

label { display: block; margin: 0 0 1em 0; }

JavaScript

new Vue({
    el: '#app',
    data: {
    	km2: 0,
        cm: 0,
        mm: 0
    },
    beforeCreate () {
    	console.log('beforeCreate')            
    },
    created () {
    	console.log('created')        
    },
    beforeMount () {
    	console.log('beforeMount')        
    },
    mounted () {
    	console.log('mounted')    
    },
    beforeUpdate () {
    	console.log('beforeUpdate')
    },
    updated () {
    	console.log('updated')
    },
    watch: {
        km2: {
        	immediate: true,
          handler (val) {
          	console.log('handler')
            this.km2 = val;
            this.cm = val * 100000;
            this.mm = val * 1000000;
					}
        },
        cm: function(val){
            this.km2 = val / 100000;
            this.cm = val;
            this.mm = val * 10;
        },
        mm: function(val){
            this.km2 = val / 1000000;
            this.cm = val / 10;
            this.mm = val;
        },
    }
});