购物车各种计算方法watch,computer(v-for循环计算多个input的值)

<template>
    <div class="layout-center">
        <ul class="nodot">
            <li  v-for="(item,index) in todo" :key="item.id">面额 {{item.value}}: 
                <input  @input="inputClick()" 
                v-model= AmountList[index] />张数 小计金额CNY:{{handleAmount(index)}}</li>
        </ul>
        <button  @click="inputClick">获取张数</button>
         <!-- watch计算 -->
        <p>通过 watch 总计金额:{{total}}</p>
        <!-- computed计算 -->
        <p>通过 computed 总计金额:{{amountTotal}}</p>
        <!-- @input -->
        <p>通过 @input 总计金额:{{valueTotal}}</p>
        <p>message: <input type="text" v-model="message"></p>
        <p>测试set get <input type="text" v-model="msg" ></p>
    </div>
</template>
<script>
export default {
    name:'Computer',
    data () {
        return {
            todo: [{id:"1",value:10}, {id:"2", value:20}, {id:"3", value:50}, {id:"4", value:100}],
            AmountList: [0,0,0,0],
            total: 0,
            valueTotal: 0,
            message:""
            
        }
    },
    //通过 watch 
    watch:{
        AmountList () {
            let sum =0;
            for( let i =0; i < this.AmountList.length; i++ ) {
                sum += this.AmountList[i] * this.todo[i].value;
            }
            this.total = sum;
        }
    },
    computed:{
        //通过computed get 属 
        amountTotal: {
            //getter
            get: function(){
                let sum = 0;
                for( let i = 0; i < this.AmountList.length; i++ ) {
                    sum += this.AmountList[i] * this.todo[i].value;
                }
                return sum;
            }
        },
        msg: {
            get:function(){
                console.log("get")
                return  "Get:" + this.message;
            },
            set: function(newVal){
                console.log("set" +newVal)
            }
        }
    },
    methods:{
        handleClick(){
            console.log(this.AmountList)
        },
        inputClick () {
            //通过@input计算总计 
            let sum =0;
            for( let i =0; i < this.AmountList.length; i++ ) {
                sum += this.AmountList[i] * this.todo[i].value
            }
            this.valueTotal = sum;
        },
        handleAmount(index){
            return this.AmountList[index] * this.todo[index].value;
        }
    }
}
</script>
<style  scoped>
 
</style>

在这里插入图片描述
watch只能监听一个数据,另一个数据改变,也就是例子中的金额不变,改变数量,小计金额随着变,要想金额和数据都改变,则要结合watch和computer
例2:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值