Vue.js 监听属性
本章节,我们将为大家介绍 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 对象创建了 data 对象的两个监控方法: kilometers 和 meters。
当我们在输入框输入数据时,watch 会实时监听数据变化并改变自身的值。可以看下如下视频演示:
 
       
bm0500
bm0***@126.com
通过vue监听事件实现一个简单的购物车
<div id="app"> <table> <tr> <th>序号</th> <th>商品名称</th> <th>商品价格</th> <th>购买数量</th> <th>操作</th> </tr> <tr v-for="iphone in Ip_Json"> <td>{{ iphone.id }}</td> <td>{{ iphone.name }}</td> <td>{{ iphone.price }}</td> <td> <button v-bind:disabled="iphone.count === 0" v-on:click="iphone.count-=1">-</button> {{ iphone.count }} <button v-on:click="iphone.count+=1">+</button> </td> <td> <button v-on:click="iphone.count=0">移除</button> </td> </tr> </table> 总价:${{totalPrice()}} </div>尝试一下 »
bm0500
bm0***@126.com
chris iven
342***472@qq.com
根据上面所写设想出自己的图书购买清单:
<div id="books"> <table> <tr> <th>序列号</th> <th>书名</th> <th>价格</th> <th>数量</th> <th>操作</th> </tr> <tr v-for="book in Books"> <td>{{ book.id }}</td> <td>{{ book.book_name }}</td> <td>{{ book.price }}</td> <td> <button v-on:click="book.count-=1">-</button> {{ book.count }} <button v-on:click="book.count+=1">+</button> </td> <td><button v-on:click="book.count=0">移除</button></td> </tr> </table> <p>总价:{{ totalPrice() }} <button v-on:click="clear()">移除所有</button> <button v-on:click="all_add_1()">所有+1</button></p> </div>尝试一下 »
chris iven
342***472@qq.com
yc488
591***846@qq.com
简单省市联动:
var vm = new Vue({ el: '#app', data: { city: '请选择', province: '请选择', provinces: ['广东', '湖南', '湖北', '北京'], cityList: [], area: [{ name: '广东', id: 1, child: ['广州', '深圳', '东莞'] }, { name: '湖南', id: 2, child: ['长沙', '株洲', '湘潭'] }, { name: '湖北', id: 3, child: ['武汉'] }, { name: '北京', id: 4, child: ['北京'] }] }, watch: { province: function(nval, oval) { var self = this; var cityList = []; if (nval == '请选择') { this.citylist = []; } if (nval != oval) { for (var i = 0; i < self.area.length; i++) { if (self.area[i].name == nval) { cityList = self.area[i].child; } } this.city = "请选择"; this.cityList = cityList; } } } })尝试一下 »
yc488
591***846@qq.com
kai
790***286@163.com
参考楼上,购物车进行加工处理(computed也可实现相同效果,且由于其依赖缓存,所以性能上更好):
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="static/js/vue.min1.js"></script> </head> <body> <div id="app"> <table> <tr> <th>序号</th> <th>商品名称</th> <th>商品价格</th> <th>购买数量</th> <th>操作</th> </tr> <tr v-for="(c, index) in commoditys" :key="index"> <td>{{ c.id }}</td> <td>{{ c.name }}</td> <td>{{ c.price | dot }}</td> <td> <input type="button" value="-" :disabled="c.count === 0" @click="c.count > 0 ? c.count-- : c.count = 0" /> {{ c.count }} <input type="button" value="+" @click="c.count++" /> </td> <td> <input type="button" value="移除" @click="c.count=0" /> </td> </tr> </table> <div> 总价:${{ totalPrice | dot }} <input type="button" value="清空" @click="clearAll" /> <input type="button" value="所有+1" @click="add" /> </div> </div> <script> const app = new Vue({ // 挂载元素 el: '#app', // 数据 data: { commoditys: [ { id: 1, name: 'iphone 8', price: 5099, count: 0 }, { id: 2, name: 'iphone xs', price: 8699, count: 0 }, { id: 3, name: 'iphone xr', price: 6499, count: 0 } ] }, // 方法 methods: { clearAll() { const len = this.commoditys.length; for (let i = 0; i < len; i++) { this.commoditys[i].count = 0; } }, add() { const len = this.commoditys.length; for (let i = 0; i < len; i++) { this.commoditys[i].count++; } } }, // 计算属性 computed: { totalPrice() { let sum = 0; const len = this.commoditys.length; for (let i = 0; i < len; i++) { sum += this.commoditys[i].price * this.commoditys[i].count; } return sum; } }, // 过滤器 filters: { dot(val) { // 简单处理保留两位小数 return `${val}.00`; } } }); </script> </body> </html>kai
790***286@163.com