<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>计算属性, 侦听器属性</title>
<script src="https://unpkg.com/vue@next"></script>
<style>
table {
width: 26em;
text-align: center;
border-collapse: collapse;
}
table caption {
font-size: 1.5em;
margin-bottom: 0.6em;
}
thead {
background-color: lightcyan;
}
th,
td {
border: 1px solid #000;
height: 2em;
}
</style>
</head>
<body>
<!-- 1. 挂载点 -->
<div class="app">
<table>
<caption>购物车</caption>
<thead>
<tr>
<th>ID</th>
<th>品名</th>
<th>单价</th>
<th>数量</th>
<th>金额</th>
</tr>
</thead>
<tbody>
<td>123</td>
<td>牛奶</td>
<td>{{price}}</td>
<td><input type="number" v-model="num"></td>
<td>{{payAmount}}</td>
</tbody>
</table>
<p>实付金额: {{disAmount}}, 优惠了: {{diffAmount}}</p>
</div>
<script>
// 2. vue实例
const app = Vue.createApp({
data() {
return {
price: 50,
num: 5,
// disAmount:0
}
},
// 计算属性: 访问器属性实现的
computed: {
// payAmount:{
// get(){
// return this.price * this.num
// },
// set(value) {
// // 通常用在测试
// }
// }
payAmount(){
// 默认就是调用访问器中的get()
return this.price * this.num;
}
},
// 侦听器属性
watch: {
// num(current,origin) {
// console.log(current, origin);
// }
// 根据用户购物金额的多少,来设置一个打折优惠
// 只需要监听用户的购物金额
payAmount(current) {
switch(true) {
case current > 1000 && current < 2000:
// this.disAmount: 打折后的金额
this.disAmount = this.payAmount * 0.9;
break;
case current >= 2000 && current < 3000:
this.disAmount = this.payAmount * 0.8
break
case current >= 3000 && current < 4000:
this.disAmount = this.payAmount * 0.7
case current >= 4000 && current < 5000:
this.disAmount = this.payAmount * 0.6
break
case current >= 5000:
this.disAmount = this.payAmount * 0.5
break;
default:
this.disAmount = this.payAmount;
}
this.diffAmount = this.payAmount - this.disAmount;
}
},
methods: {
},
// 生命周期:
mounted() {
this.num = 1;
},
});
// 3. vue实例与挂载点绑定/关联起来
app.mount('.app')
</script>
</body>
</html>