- 监听属性实现计数器
<body>
<div id="app">
<p>计时器:{{count}}</p>
<button @click="count++" >点我</button>
</div>
<script>
var vm = new Vue({
el: "#app",
data: {
count:1
}
})
vm.$watch('count', function (nval,oval) {
alert('oval:' + oval + ' nval:' + nval);
});
</script>
</body>
- 监听属性实现km和m转换
<body>
<div id="app">
千米: <input type="text" v-model="kiloMeters" value="0">
米: <input type="text" v-model="meters" value="0">
<p id="info"></p>
</div>
<script>
var vm = new Vue({
el: "#app",
data: {
kiloMeters : 0,
meters: 0
},
watch: {
kiloMeters: function (nval) {
this.meters = nval*1000;
},
meters: function (nval) {
this.kiloMeters = (nval/1000.0);
}
}
})
vm.$watch('kiloMeters', function (nval, oval) {
document.getElementById("info").innerHTML = 'oval:'+oval + ' naval:'+nval;
});
</script>
- 监听事件实现购物车
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>
<script src="https://cdn.staticfile.org/vue/2.4.2/vue.min.js"></script>
<style>
table{
border: 1px solid black;
width: 100%;
}
th{
height: 50px;
}
th,td{
border-bottom: 1px solid #ddd;
}
th,td{
text-align: center;
}
</style>
</head>
<body>
<div id="app">
<table >
<tr>
<th>序号</th>
<th>商品名称</th>
<th>商品价格</th>
<th>购买数量</th>
<th>操作</th>
</tr>
<tr v-for="item in jsonData">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.price}}</td>
<td>
<button :disabled="item.count === 0" @click="item.count-=1">-</button>
{{item.count}}
<button @click="item.count+=1">+</button>
</td>
<td>
<button @click="item.count = 0">移除</button>
</td>
</tr>
</table>
<p>总价:${{totalMoney()}}</p>
</div>
<script>
var vm = new Vue({
el: "#app",
data: {
jsonData: [{
id: 1,
name: 'iphone 8',
price: 5099,
count: 1
},
{
id: 2,
name: 'iphone xs',
price: 8699,
count: 1
},
{
id: 3,
name: 'iphone xr',
price: 6499,
count: 1
}]
},
methods:{
totalMoney: function () {
var total = 0;
for (var i = 0; i<this.jsonData.length; i++) {
total+=(this.jsonData[i].price*this.jsonData[i].count);
}
return total;
}
}
})
</script>
</body>
</html>