父子组件传参中的子传父

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

html部分:

<div id='app'>
<father></father>//组件名
</div> 

插件

//父插件
<template id='father'>
	<div>
	<son @tofather='tofather'></son>//	在父组件中给引用的子组件注册一个事件(这个事件的名字是自定义的)
	</div>
</template>

//子插件
<template id='son'>
	<div>
	<button @click="tofa">toFa</button>
	</div>
</template>

js部分

  // 父组件
        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() {
    
    
                    // 第一个参数:自定义的名字
                    //第二个参数:传递的数据  只能传入两个值 第三个为undefined
                    // 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: {
    
    
            }
        })

猜你喜欢

转载自blog.csdn.net/qq_52654932/article/details/130694023