ylbtech-Vue.js:监听属性 |
1.返回顶部 |
1、
Vue.js 监听属性
本章节,我们将为大家介绍 Vue.js 监听属性 watch,我们可以通过 watch 来响应数据的变化:
实例
<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 = val * 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。
当我们再输入框输入数据时,watch 会实时监听数据变化并改变自身的值。可以看下如下视频演示:
2、
2.返回顶部 |
3.返回顶部 |
4.返回顶部 |
5.返回顶部 |
1、
2、
6.返回顶部 |
![]() |
作者:ylbtech 出处:http://ylbtech.cnblogs.com/ 本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。 |