zoukankan      html  css  js  c++  java
  • 42.VUE学习之--组件之子组件使用$on与$emit事件触发父组件实现购物车功能

    <!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">
        <hd-news :lists="goods" @sum="total"></hd-news>
        总计:{{totalPrice}}元
    </div>
    <script type="text/x-template" id="hdNews">
        <table border="1" width="90%">
            <tr>
                <th>商品名称</th><th>商品价格</th><th>商品数量</th>
            </tr>
            <tr v-for="(v,k) in lists">
                <td>{{v.title}}</td><td>{{v.price}}</td>
                <td>
                    <!--当input失去焦点时,会呼叫子组件里的sum()方法,sum()方法再通过@sum属性呼叫父组件里的tatal方法,从而再次执行计算-->
                    <input type="text" v-model="v.num" @blur="sum">
                </td>
            </tr>
        </table>
    </script>
    <script>
        var hdNews = {
            template: "#hdNews",
            props: ['lists'],
            methods:{
                sum(){
                    this.$emit('sum');
                }
            }
        };
        new Vue({
            el: '#hdcms',
            components: {hdNews},
            //页面加载完后,加自动执行total里的方法
            mounted(){
                this.total();
            },
            data: {
                totalPrice:0,
                goods:[
                    {title:'iphone7Plus',price:100,num:1},
                    {title:'后盾人会员',price:200,num:1},
                ]
            },
            methods:{
                total(){
                    this.totalPrice=0;
                    this.goods.forEach((v)=>{
                        this.totalPrice+=v.num*v.price;
                    })
                }
            }
        });
    </script>
    </body>
    </html>
    

    效果:

    [Haima的博客] http://www.cnblogs.com/haima/
  • 相关阅读:
    Spring-Cloud-GateWay
    Spring-Clould-Alibaba-sentinel控制台
    Oacle学习-01Oracle的安装
    Spring-Clould-Alibaba-集成Ribbon&Feign
    Spring-Clould-Alibaba-nginx-nacos集群搭建
    Springboot整合Security
    Springboot实现QQ邮箱的发送
    java实现qq邮箱的发送
    Springboot集成Swagger2
    Hadoop集群搭建
  • 原文地址:https://www.cnblogs.com/haima/p/10238459.html
Copyright © 2011-2022 走看看