<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>计算属性-侦听器属性</title>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></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>
<div class="app">
<table>
<caption>购物车</caption>
<thead>
<tr>
<th>ID</th>
<th>品名</th>
<th>单价</th>
<th>数量</th>
<th>金额</th>
</tr>
<tbody>
<td>123</td>
<td>牛奶</td>
<td>{{price}}</td>
<td><input type="number" v-model="num"></td>
<td>{{payAmount}}</td>
</tbody>
</thead>
</table>
<p>实付金额:{{disAmount}},优惠了:{{diffAmount}}</p>
</div>
<script>
const app = Vue.createApp({
data() {
return {
price: 50,
num: 5,
//disAmount: 0
}
},
//计算属性 :访问器属性实现的
computed: {
// payAmount: {
// get() {
// return this.price * this.num
// },
// set(value) {
// //通常用在测试
// this.price = value / this.num
// }
// }
payAmount() {
//默认就是i调用访问器中的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
break
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
}
}).mount('.app')
</script>
</body>
</html>
最后修改:2025 年 04 月 08 日
© 允许规范转载
此处评论已关闭