Vue(八):监听属性watch

时间:2023-03-09 13:09:09
Vue(八):监听属性watch

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

Vue(八):监听属性watch