·子组件触发事件时可以向父组件传值

    自定义事件传值 - 图1

    ·父组件在监听事件时需要接收子组件传递的数据。

    自定义事件传值 - 图2

    自定义事件传值 - 图3

    <!DOCTYPE html> <html lang=“en”> <head> <meta charset=“UTF-8”> <meta name=“viewport” content=“width=device-width, initial-scale=1.0”> <title>Document</title> </head> <body> <div id=“app”> <h3>购物车</h3> <product-item v-for=“product in products” :key=“product.id” :title=“product.title” @count-change=“onCountChange” ></product-item> <p>商品总个数为:{{ totalCount }}</p> </div> <script src=“lib/vue.js”></script> <script> // 子组件 Vue.component(‘ProductItem’, { props: [‘title’], template: `
    商品名称: {{ title }}, 商品个数: {{ count }}
    `, data () { return { count: 0 } }, methods: { countIns1 () { this.$emit(‘count-change’, 1); this.count++; }, countIns5 () { this.$emit(‘count-change’, 5); this.count += 5; } } }); // 父组件 new Vue({ el: ‘#app’, data: { products: [ { id: 1, title: ‘苹果一斤’ }, { id: 2, title: ‘香蕉一根’ }, { id: 3, title: ‘橙子一个’ } ], totalCount: 0 }, methods: { onCountChange (productCount) { this.totalCount += productCount; } } }); </script> </body> </html>