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>

效果:

posted @ 2019-01-08 13:27  HaimaBlog  阅读(142)  评论(0编辑  收藏  举报