监听属性
Vue.js 监听属性 watch,通过 watch 来响应数据的变化
使用watch实现计算美元对黄金汇率
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script type="text/javascript" src="vue.min.js" ></script>
<style>
table tr td{
border:1px solid gray;
padding:10px;
}
table{
border-collapse:collapse;
width:800px;
table-layout:fixed;
}
tr.list{
background-color: lightGray;
}
</style>
</head>
<body>
<div id="div1">
<table align="center">
<tr class="list">
<th>美元</th>
<td>黄金</td>
</tr>
<tr>
<td align="center" colspan="2">
汇率:<input type="number" v-model.number="change"/>
</td>
</tr>
<td align="center">
$:<input type="number" v-model.number = "dollar"/>
</td>
<td align="center">
盎司:<input type="number" v-model.number = "ounce"/>
</td>
</table>
</div>
<script>
new Vue({
el:'#div1',
data:{
change:1200,
dollar:0,
ounce:0
},
watch:{
dollar:function(val){
this.dollar = val;
this.ounce = this.dollar / this.change;
},
ounce:function(val){
this.ounce = val;
this.dollar = this.ounce * this.change;
},
}
})
</script>
</body>
</html>
通过vue监听事件实现一个简单的购物车
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="vue.min.js"></script>
</head>
<style>
table {
border: 1px solid black;
}
table {
width: 25%;
}
th {
height: 50px;
}
th, td {
padding-left:30px;
border-bottom: 1px solid #ddd;
}
</style>
<body>
<div id="app">
<table>
<tr>
<th>编号</th>
<th>商品名称</th>
<th>商品价格</th>
<th>购买数量</th>
<th>操作</th>
</tr>
<tr v-for="redmi in json">
<td>{{redmi.id}}</td>
<td>{{redmi.name}}</td>
<td>{{redmi.price}}</td>
<td>
<button v-bind:disabled="redmi.count === 0" v-on:click="redmi.count-=1">-</button>
{{redmi.count }}
<button v-on:click="redmi.count+=1">+</button>
</td>
<td>
<button v-on:click="redmi.count=0">清空</button>
</td>
</tr>
</table>
总价:¥{{total()}}
</div>
</body>
<script>
var app = new Vue({
el: '#app',
data: {
json: [{
id: 1,
name: '红米4A',
price: 699,
count: 1
},
{
id: 2,
name: '红米5A',
price: 799,
count: 1
},
{
id: 3,
name: '红米6A',
price: 899,
count: 1
}]
},
methods:{
total : function(){
var test = 0;
for (var i = 0,len = this.json.length;i<len;i++) {
test+=this.json[i].price*this.json[i].count;
}
return test;
}
}
})
</script>
</html>