<template>
<div class="container">
<input v-model="firstName" type="text">
<input v-model="lastName" type="text">
<h2>{{ name }}</h2>
<table border style="width: 600px;text-align: center;">
<thead>
<th>名称</th>
<th>数量</th>
<th>单价</th>
<th>操作</th>
</thead>
<tbody>
<tr v-for="(item, index) in data" :key="index">
<td>{{ item.name }}</td>
<td> <button @click="controlNum(item, false)">-</button> {{ item.num }}
<button @click="controlNum(item, true)">+</button>
</td>
<td>{{ item.num * item.price }}</td>
<td>
<button @click="delGoods(index)">删除</button>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td></td>
<td></td>
<td></td>
<td>总价: {{sumNum}}</td>
</tr>
</tfoot>
</table>
</div>
</template>
<script setup>
import { ref, computed, reactive } from 'vue'
let firstName = ref('')
let lastName = ref('')
const name = computed(() => {
return firstName.value + '---' + lastName.value
})
const data = reactive([
{ name: '老6', num: 1, price: 1000 },
{ name: '老6的衣服', num: 2, price: 50 },
{ name: '老6的裤子', num: 3, price: 90 },
])
// 增减绑定一个按钮 通过type值判断增加还是减少
const controlNum = (item, type) => {
if (item.num > 1 && !type) {
item.num--
}
if (item.num < 99 && type) {
item.num++
}
}
// 从第几项开始删除,删除几个
// 从index项开始删除,删除一个
const delGoods = (index) => {
data.splice(index, 1)
}
// 计算总价
// 缺点 无法实时计算
// let sumNum = ref(0)
const total = () => {
// prev是上一次的值,这里还未进行循环,让他默认为0
sumNum.value = data.reduce((prev,item) => {
return prev + (item.num * item.price)
},0)
}
// 使用computed来实现实时计算
let sumNum = ref(0)
sumNum = computed(() => {
return data.reduce((prev,item) => {
return prev + (item.num * item.price)
},0)
})
</script>
<style lang="scss" scoped>
.container {
width: 100%;
height: 500px;
border: 2px solid #ccc;
}
</style>
vue3.2的computed属性增改合计小demo
于 2022-07-18 16:08:52 首次发布