vue3 利用computer 自动计算属性
Posted 安果移不动
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了vue3 利用computer 自动计算属性相关的知识,希望对你有一定的参考价值。
<template>
<div>
<table border style="width:800px">
<thead>
<tr>
<th>名称</th>
<th>数量</th>
<th>单价</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in data" :key="index">
<td align="center">
item.name
</td>
<td align="center">
<button @click="addAndSub(item,true)">+</button>
item.number
<button @click="addAndSub(item,false)">-</button>
</td>
<td align="center">
item.price
</td>
<td align="center">
<el-button type="danger" @click="deleteRow(index)">删除</el-button>
</td>
</tr>
</tbody>
<tfoot>
<td></td>
<td></td>
<td></td>
<td>总价: total </td>
</tfoot>
</table>
</div>
</template>
<script setup lang="ts">
import computed, reactive, ref from 'vue';
type Shop =
name: string;
number: number;
price: number;
;
const data = reactive<Shop[]>([
name: '苹果',
number: 10,
price: 5.5,
,
name: '香蕉',
number: 20,
price: 2.5,
,
name: '橘子',
number: 30,
price: 3.5,
,
name: '西瓜',
number: 40,
price: 4.5,
,
name: '草莓',
number: 50,
price: 6.5,
,
name: '葡萄',
number: 60,
price: 7.5,
,
name: '梨',
number: 70,
price: 8.5,
,
name: '樱桃',
number: 80,
price: 9.5,
,
name: '橙子',
number: 90,
price: 10.5,
,
name: '柠檬',
number: 100,
price: 11.5,
,
name: '芒果',
number: 110,
price: 12.5,
,
name: '火龙果',
number: 120,
price: 13.5,
,
name: '榴莲',
number: 130,
price: 14.5,
,
name: '荔枝',
number: 140,
price: 15.5,
,
name: '桃子',
number: 150,
price: 16.5,
,
name: '李子',
number: 160,
price: 17.5,
,
name: '椰子',
number: 170,
price: 18.5,
,
name: '樱桃',
number: 180,
price: 19.5,
,
name: '橙子',
number: 190,
price: 20.5,
,
name: '柠檬',
number: 200,
price: 21.5,
,
name: '芒果',
number: 210,
price: 22.5,
,
name: '火龙果',
number: 220,
price: 23.5,
,
name: '榴莲',
number: 230,
price: 24.5,
,
name: '荔枝',
number: 240,
price: 25.3,
,
]);
const addAndSub = (item: Shop, isAdd: boolean) =>
if (isAdd)
item.number++;
else
if (item.number > 0)
item.number--;
;
const total = computed(() =>
return data.reduce((pre, cur) =>
return pre + cur.number * cur.price;
, 0);
);
const deleteRow = (index: number) =>
data.splice(index, 1);
;
</script>
以上是关于vue3 利用computer 自动计算属性的主要内容,如果未能解决你的问题,请参考以下文章