首页 > 其他 > 详细

Vue(八):监听属性watch

时间:2019-01-06 19:36:13      阅读:196      评论:0      收藏:0      [点我收藏+]

 Vue.js 可以通过 watch 来响应数据的变化。

以下实例模拟购物车里商品数量增加,对应价格也增加

       <!--模拟购物车商品数量增加,价格也随之增加-->
<div id = "app"> <h3>Search Goods</h3> <input type=‘goodsname‘ v-model="goodsname" /> <br><br> <table border=1> <tr> <th>goodsname</th> <th>spnums</th> </tr> <tr> <td>{{goodsname}}</td> <td>{{spnums}}</td> </tr> </table> <hr> <p style="color:red">{{msg}}</p> <h3>Shopping Cart</h3> <p>apple: {{ num }} </p> <p>price: {{ price }}</p> <button @click = "num++" >add apple num</button> </div> <script type = "text/javascript"> var randomnum = Math.floor(Math.random()*100); var vm = new Vue({ el: ‘#app‘, data: { num: randomnum, price:156, msg:‘‘, goodsname:‘‘, spnums:randomnum }, watch:{ goodsname:function(val){ if(val==‘a‘ || val==‘ap‘ || val==‘app‘ || val==‘appl‘ || val==‘apple‘){ this.goodsname=‘apple‘; }else{ alert(‘no result!‘); } } } });
      // $watch是一个实例方法 vm.$watch(
‘num‘, function(nval, oval) { this.spnums--; this.msg="cart apple num add,from "+oval+" to "+nval+",so price change to "+(this.price+=10) }); </script>

技术分享图片

 技术分享图片

 

Vue(八):监听属性watch

原文:https://www.cnblogs.com/shamo89/p/10217051.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!