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/
  • 相关阅读:
    第二章
    第一章
    unity--实现新手引导功能
    golang MissingContentLength error
    遇到一个golang time.Tick的坑
    grpc client连接池及负载均衡实现
    Pytorch学习-线性回归
    Pytorch学习-自动求导
    Pytorch学习-线性代数实现
    天池Python训练营笔记—Python基础进阶:从函数到高级魔法方法
  • 原文地址:https://www.cnblogs.com/haima/p/10238459.html
Copyright © 2011-2022 走看看