Vue.js 监听属性 watch,我们可以通过 watch 来响应数据的变化。

以下实例通过使用 watch 实现计数器:

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

-----------也可以改成-------------------

<div id = "app">
    <p style = "font-size:25px;">计数器: {{ counter }}</p>
   <!-- <button @click = "counter++" style = "font-size:25px;">点我</button>-->
    <button @click = "countClick" style = "font-size:25px;">点我</button>
</div>
</body>
</html>
<script type = "text/javascript">
    var vm = new Vue({
        el: '#app',
        data: {
            counter: 1
        },
       methods:{
            countClick: function(){
              return this.counter ++;
            }
       }


    });
   vm.$watch('counter', function(nval, oval) {
        alert('计数器值的变化 :' + oval + ' 变为 ' + nval + '!');
    });
</script>
Logo

前往低代码交流专区

更多推荐