$watch()监听

demo1:监听counter的变化

<div id="app">
        <p style="font-size: 25px;">计数器:{{ counter }}p>
        <button @click="counter++" style="font-size: 25px;">点我button>
div>
 const app = new Vue({
            el:"#app",
            data:{
                counter:1
            }
        });
        app.$watch('counter', function(nval,oval){
            console.log('计数器值的变化为:' + oval + '变为' + nval +'!')
        })

demo2:监听千米,米之间的转换

<div id="app">
        千米:
        米:
div>
 const vm = new Vue({
            el:"#app",
            data:{
                kilometers:0,
                meters:0
            },
            methods: {
                
            },
            computed: {
                
            },
            watch: {
                kilometers:function(val) {
                  this.kilometers = val;
                  this.meters = this.kilometers * 1000
               },
                meters:function (val) {
                    this.kilometers = val/ 1000;
                    this.meters = val;
                }
            }
        });
        vm.$watch('kilometers', function(nval,oval){
            console.log("修改前为:" + oval + "修改后为" + nval );
            
        })
        vm.$watch('meters', function(nval,oval){
            console.log("修改前为:" + oval + "修改后为" + nval );
            
        })

你可能感兴趣的:($watch()监听)