computed属性

计算属性就是当依赖的值发生变化的时候,才会触发它的更改,如果依赖的值不发生变化的时候,使用的是缓存中的值

简易的购物车

Tips:利用函数的形式来完成数值的变化

<template>
  <div>
    <div>简易购物车</div>
  </div>
  <table border="1" width="500px">
    <thead>
    <tr>
      <th>名称</th>
      <th>数量</th>
      <th>价格</th>
      <th>单件总价</th>
    </tr>
  </thead>
  <tbody>
    <tr v-for="(item,index) in products"  :key="index" >
      <td align="center">{{ item.names }}</td>
      <td align="center"><button @click="change_count(item,false)">-</button>{{ item.count }}<button @click="change_count(item,true)">+</button></td>
      <td align="center">{{ item.price * item.count }}</td>
      <td align="center"><button @click="deletes(index)">删除</button></td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td></td>
      <td></td>
      <td></td>
      <td align="center">总价:¥{{ $total }}</td>
    </tr>
  </tfoot>
  </table>
 
  <div>
    <button @click="change">测试</button>
  </div>
</template>

<script setup lang="ts">
import { reactive,ref} from 'vue';
type demo = {
  names:string,
  count:number,
  price:number
}
let $total = ref(0)
const products = reactive<demo[]>([{
  names:'衣服',
  count:1,
  price:288
},{
  names:'裤子',
  count:1,
  price:212
},{
  names:'鞋子',
  count:1,
  price:388
},])
// 数量加减函数
const change_count =(item:demo,type:boolean):void=>{
  if(item.count>1 && !type){
    item.count--
  }
  if(item.count<10 && type){
    item.count++
  }
totlal()

}

// 删除物品
const deletes = (index:number )=>{
  products.splice(index,1)
  totlal()

}

const change = ()=>{
  console.log(products);
}

// 计算商品总和
const totlal = ()=>{
  $total.value = products.reduce((pre,next) =>{
    return pre + next.count*next.price
  },0)
}
totlal()

</script>

<style scoped>

</style>
 
===============================================================================
Tips:利用computed属性来完成:
不用多次调用函数,一次性完成

 

 

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
posted @   sixpence1016  阅读(22)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示