Vue.js 监听属性

Vue.js 教程 · 2019-04-02 15:18:33

本章节,我们将为大家介绍 Vue.js 监听属性 watch,我们可以通过 watch 来响应数据的变化。

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

实例

<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 = "computed_props"> 千米 : <input type = "text" v-model = "kilometers"> 米 : <input type = "text" v-model = "meters"> </div> <p id="info"></p> <script type = "text/javascript"> var vm = new Vue({ el: '#computed_props', 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; } } }); // $watch 是一个实例方法 vm.$watch('kilometers', function (newValue, oldValue) { // 这个回调将在 vm.kilometers 改变后调用 document.getElementById ("info").innerHTML = "修改前值为: " + oldValue + ",修改后值为: " + newValue; }) </script>

以上代码中我们创建了两个输入框,data 属性中, kilometers 和 meters 初始值都为 0。watch 对象创建了两个方法 kilometers 和 meters。

点击查看所有 Vue.js 教程 文章: https://www.codercto.com/courses/l/38.html

查看所有标签

APIs

APIs

Daniel Jacobson、Greg Brail、Dan Woods / O'Reilly Media / 2011-12-24 / USD 24.99

Many of the highest traffic sites get more than half of their traffic not through the browser but through the APIs they have created. Salesforce.com (more than 50%) and Twitter (more than 75% fall int......一起来看看 《APIs》 这本书的介绍吧!

随机密码生成器
随机密码生成器

多种字符组合密码

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具