1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
| <template> <div> <div> <input v-model="keyWord" placeholder="搜索" type="text"> </div> <div style="margin-top: 20px;"> <table border width="600" cellpadding="0" cellspacing="0"> <thead> <tr> <th>名称</th> <th>单价</th> <th>数量</th> <th>总价</th> <th>操作</th> </tr> </thead> <tbody> <!-- <tr v-for="(item, index) in data" :key="index"> --> <tr v-for="(item, index) in searchData" :key="index"> <td align="center">{{ item.name }}</td> <td align="center">{{ item.price }}</td> <td align="center"> <button @click="sub(item)">-</button> {{ item.num }} <button @click="add(item)">+</button> </td> <td align="center">{{ item.num*item.price }}</td> <td align="center"><button @click="del(index)">删除</button></td> </tr> </tbody> <tfoot> <tr> <td colspan="5" align="right"> <!-- 总价:{{ $total }} --> 总价:{{ total }} </td> </tr> </tfoot> </table> </div> </div> </template>
<script setup lang="ts"> import { ref, computed, reactive } from 'vue'
interface Data { name: string, price: number, num: number, } let keyWord = ref<string>("")
let data = reactive<Data[]>([ { name: "KNN", price: 114, num: 1, }, { name: "SNNN", price: 514, num: 1, }, { name: "YJSP", price: 1919, num: 1, }, { name: "RU", price: 810, num: 1, }, { name: "BNKRG", price: 364, num: 1, }, { name: "YMN", price: 364, num: 1, }, ])
// 使用函数方式计算总价 // let $total = ref<number>(0) // const total = ()=> { // $total.value = data.reduce((prev: number, next: Data)=> { // return prev+next.num*next.price // }, 0) // } // 程序开始时、物品数量增删改时,都要调用这个函数,很麻烦 // total()
// 使用computed就很省心了 const total = computed(()=> { return data.reduce((prev: number, next: Data)=> { return prev+next.num*next.price }, 0) }) // 还可与用来过滤数据 const searchData = computed(()=> { return data.filter((item:Data)=> { return item.name.includes(keyWord.value) }) })
const sub = (item: Data)=> { // return item.num>1?(item.num--,total()):null return item.num>1?item.num--:null } const add = (item: Data)=> { // return item.num<99?(item.num++,total()):null return item.num<99?item.num++:null } const del = (index: number)=> { data.splice(index,1) // total() } </script>
|