10-组件通信-子传父(自定义函数)

本文详细介绍了如何使用Vue.js实现子组件通过自定义事件将数据传递给父组件,通过实例展示了`v-for`遍历和`$emit`触发事件的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

10-组件通信-子传父(自定义函数)

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>组建通信-子传父(自定义函数)</title>
</head>

<body>
    <!-- 父组件模板 -->
    <div id="app">
        <cpn @item-click="cpnClick"></cpn>
    </div>

    <!-- 子组件模板 -->
    <template id="cpn">
        <div>
            <button v-for="item in catagories" @click="btnClick(item)">{{item.name}}
            </button>
        </div>
    </template>

    <script src="../js/vue.js"></script>
    <script>

        // 1,子组件
        const cpn = {
            template: '#cpn',
            data() {
                return {
                    catagories: [
                        { id: "aaa", name: "热门推荐" },
                        { id: "bbb", name: "手机数码" },
                        { id: "ccc", name: "家用家电" },
                        { id: "ddd", name: "电脑电视" },
                    ]
                }
            },
            methods: {
                // 发射事件:自定义事件
                btnClick(item) {
                    this.$emit('item-click', item)
                }
            }
        }

        // 2,父组件
        const app = new Vue({
            el: '#app',
            data: {
                info: {
                    name: 'coderwhy',
                    age: 19,
                    height: 1.99
                }
            },
            components: {
                cpn
            },
            methods: {
                cpnClick(item) {
                    console.log(item);
                }
            }
        })
    </script>
</body>

</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

林笙10

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值