菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

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

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

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

入驻
27
0

购物车实现一

原创
05/13 14:22
阅读数 34600

使用子组件触发事件时通过this.$emit来发送给父组件从而调用父组件的方法来修改总价

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <title>Title</title>
    <!-- Bootstrap -->
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
    <script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script type="text/javascript" src="./node_modules/vue/dist/vue.js"></script>
    <script type="text/javascript" src="./node_modules/vue-router/dist/vue-router.js"></script>
    <script type="text/javascript" src="./node_modules/axios/dist/axios.js"></script>

</head>
<body>
<div id="box">
    <div class="text-info"><h4>购物车</h4></div>
    <rk-cart :goods="goods"  @sum="total"></rk-cart>

    <div>
        合计:{{totalPrice}}元
    </div>

</div>

<script type="text/x-template" id="cart">
    <table border="1" width="90%">
        <tr>
            <th>序号</th>
            <th>名称</th>
            <th>价格</th>
            <th>数量</th>
            <th>操作</th>
        </tr>

        <tr v-for="(item,key) in goods">
            <td>{{item.id}}</td>
            <td>{{item.goodsName}}</td>
            <td>{{item.price}}</td>
            <td>
                <input type="text" v-model="item.num" @blur="sum">
            </td>
            <td>删除</td>
        </tr>
    </table>
</script>

<script type="text/javascript">

    let rkCart = {
        methods:{
            sum(){
                console.log('sum');
                this.$emit('sum');
            }
        },
        props:['goods'],
        template:'#cart'
    };

    let app = new Vue({
        el:'#box',
        mounted(){
            this.total();
        },
        data:{
            goods:[
                {id:1,goodsName:'iphone 8 Plus',price:6900,num:1},
                {id:2,goodsName:'爱奇艺vip',price:100,num:1},
            ],
            totalPrice:0,
        },
        components:{rkCart},
        methods:{
            total(){
                this.totalPrice = 0;
                this.goods.forEach(v=>{
                    this.totalPrice += v.price * v.num;
                });
            }
        }
    });
</script>
</body>
</html>

  

发表评论

0/200
27 点赞
0 评论
收藏