Vue笔记-组件Component-组件通信之子组件向父组件传递

组件通信之子组件向父组件传递

子向父传值需要通过自定义事件实现

  • 子组件定义方法,通过$emit方法触发count-change(自定义事件)事件,并传递参数(可选)
  • 父级视图绑定count-change(自定义事件)事件,通过$event接收数据,也可也触发父级的方法通过参数接收数据

示例

    <div id="app">
        <!-- 视图绑定count-change事件,通过$event接收数据,也可也触发父级的方法通过参数接收数据 -->
        <!-- @count-change='count+=$event' 可以直接在视图中通过$event接收数据 -->
        <my-com v-for='tem in tems' :key="tem.key" :title='tem.title' @count-change='countnum'>
        </my-com>
        <p>总数:{{ count }}</p>
    </div>
<script src="./node_modules/vue/dist/vue.js"></script>
    <script>
        Vue.component('myCom', {
            props: ['title'],
            template: `
            <div>
                <span>商品: {{ title }} 数量:{{ num }}</span>
                <button @click = 'countadd1'>+1</button>
                <button @click = 'countadd3'>+3</button>
            </div>
            `,
            data() {
                return {
                    num: 0
                }
            },
            // 子组件定义方法,通过$emit方法触发count-change事件,并传递参数(可选)
            methods: {
                countadd1() {
                    this.$emit('count-change', 1);
                    this.num++
                },
                countadd3() {
                    this.$emit('count-change', 3);
                    this.num += 3;
                }
            },
        })

        new Vue({
            el: '#app',
            data: {
                tems: [{
                        id: 1,
                        title: '苹果'
                    },
                    {
                        id: 2,
                        title: '橙子'
                    },
                    {
                        id: 3,
                        title: '香蕉'
                    }
                ],
                count: 0,
            },
            methods: {
                // 通过参数event接收,子级传送过来的数据
                countnum(event) {
                    this.count += event;
                }
            },
        })
    </script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值