Vue中父子组件传值

子组件调用父组件的方法:

  1. 在父组件中给引用的子组件注册一个事件(这个事件的名字是自定义的) 相当于给两个组件直接建立联系
  2. 子组件可以触发这个事件$emit(‘事件名字’)
子组件给父组件传递数据:
  1. $emit方法第二个参数可以定义子组件给父组件传递的内容
    在父组件中怎么拿到这内容
  2. 父组件这个方法没有自定参数,在父组件的方法直接加这个参数就可以拿到
  3. 父组件有自定义参数,可以传入event也可以拿到子组件传递的数据。通过 event也可以拿到子组件传递的数据。通过event也可以拿到子组件传递的数据。通过event只能传递第一个参数。

子传父传值后把值渲染在视图层

子组件为app 父组件为标间father

    <div id='app'>
                <father></father>
    </div>

//自定义father组件
    <template id="father">
        <div>
            <son :toson="toSon" @tofather="tofather($event,1)"></son>
        </div>
    </template>
//自定义son组件
    <template id="son">
        <div>
            <button @click="toFather">toFather</button>
            {{msg}}
        </div>
    </template>


    
 <script>
 //定义father组件
        Vue.component('father', {
            template: '#father',
            data() {
                return {
                    toSon: { name: 1 }
                }
            },
            methods: {
                tofather(data, params) {
                    console.log(data);
                    console.log(params);
                    console.log(event);
                }
            }
        })
//自定义son组件
        Vue.component('son', {
            template: '#son',
            data() {
                return {
                    msg: ''
                }
            },
            props: {
                toson: [String, Number, Object],
                toson: {
                    type: [String, Number],
                    dafault() {
                        return {

                        }
                    }
                }
            },
            methods: {
                toFather() {
                    // 第一个参数:自定义事件名  第二个参数:要传递的参数
                    this.$emit('tofather', '去father', '去father2')
                    // this.$emit('tofather', { name: 'zs' })
                }
            },
            created() {
                // this.$emit('tofather', '去father')
                // this.toson = 'father'
                // console.log(this.toson);
                this.msg = this.toson
            }
        })
        const vm = new Vue({
            el: '#app',
            data: {
            },
            methods: {
            }
        })
    </script>

---




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值