菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
312
0

43.VUE学习之--组件之使用.sync修饰符与computed计算属性超简单的实现美团购物车原理

原创
05/13 14:22
阅读数 61004
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <!--<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>-->
    <script type="text/javascript" src="../js/vue.js"></script>
</head>
<body>
<div id="hdcms">
    <!-- .sync 当数据改变时,会自动把子组件里的值赋值到父组件goods里,当goods的值改变时,totalPrice又会重新计算-->
    <hd-news :lists.sync="goods" ></hd-news>
    总计:{{totalPrice}}元
</div>
<script type="text/x-template" id="hdNews">
    <table border="1" width="90%">
        <tr>
            <th>商品名称</th><th>商品价格</th><th>商品数量</th><th>合计</th>
        </tr>
        <tr v-for="(v,k) in lists">
            <td>{{v.title}}</td>
            <td><input type="text" v-model="v.price"></td>
            <td>
                <input type="text" v-model="v.num">
            </td>
            <td>{{v.price*v.num}}</td>
        </tr>
    </table>
</script>
<script>
    var hdNews = {
        template: "#hdNews",
        props: ['lists']
    };
    new Vue({
        el: '#hdcms',
        components: {hdNews},
        //页面加载完后,加自动执行
        computed:{
            totalPrice(){
                var sum=0;
                this.goods.forEach((v)=>{
                    sum+=v.num*v.price;
                })
                return sum;
            }
        },
        data: {
            goods:[
                {title:'iphone7Plus',price:100,num:1},
                {title:'后盾人会员',price:200,num:1},
            ]
        }
    });
</script>
</body>
</html>

效果:

发表评论

0/200
312 点赞
0 评论
收藏