父子组件传参

父子组件传参

前言

`子组件调用父组件的方法
1. 在父组件中给引用的子组件注册一个事件(这个事件的名字是自定义的)
2. 子组件可以触发这个事件$emit(‘事件名字’)

        子组件给父组件传递数据
        1.	$emit方法第二个参数可以定义子组件给父组件传递的内容
        2.	在父组件中怎么拿到这内容
        2.1 父组件这个方法没有自定参数,在父组件的方法直接加这个参数就可以拿到
        2.2 父组件有自定义参数,可以传入$event也可以拿到子组件传递的数据。通过$event只能传递第一个参数。

1.

代码如下(示例):

<div id='app'>

        <father></father>
    </div>

    <template id="father">
        <div>
            <son :type="type1" @tofather="tofather1(1,$event)"></son>
        </div>
    </template>

    <template id="son">

        <div>son
            <button @click="toFa">toFa</button>
        </div>
    </template>

2.

代码如下(示例):

// 父组件
        Vue.component('father', {
            template: '#father',
            data() {
                return {
                    type1: 'free'
                }
            },
            methods: {
                // 接收来自子组件的传值
                tofather1(data, data2) {
                    console.log(data);
                    console.log(data2);
                }
            }
        })


        // 子组件
        Vue.component('son', {
            template: '#son',
            data() {
                return {

                }
            },
            props: {
                type: {
                    type: [String, Number],
                    default: () => {
                        return 'free'
                    }
                }
            },
            methods: {
                toFa() {
                    // 第一个参数:自定义的名字
                    //第二个参数:传递的数据
                    // this.$emit('tofather', '传过去的数据')
                    this.$emit('tofather', { name: 'zs', age: 18 })
                }
            },
            created() {
                // this.$emit('tofather', { name: 'zs', age: 18 })

                console.log(this.type);
            }
        })
        const vm = new Vue({
            el: '#app',
            data: {
            },
            methods: {
            }
        })
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值