首页 > 其他分享 >computed属性

computed属性

时间:2023-01-05 18:11:15浏览次数:28  
标签:count const computed price item products names 属性

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

简易的购物车

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属性来完成: 不用多次调用函数,一次性完成

 

 

                                         

标签:count,const,computed,price,item,products,names,属性
From: https://www.cnblogs.com/sixpence1016/p/17028518.html

相关文章