Passing parameters from son to parent in parent-child component

Method steps:
The child component calls the method of the parent component
1. Register an event in the parent component for the referenced child component (the name of this event is customized)
2. The child component can trigger this event $emit('event name')
Subcomponent passes data to parent component
1. The second parameter of the $ emit method can define the content passed by the subcomponent to the parent component
2. How to get this content in the parent component
2.1 This method of the parent component has no custom parameters. You can get 2.2 by directly adding this parameter to the method.
The parent component has custom parameters. You can pass in $event and get the data passed by the child component. Only the first parameter can be passed through $event.

html part:

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

plug-in

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

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

js part

  // 父组件
        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: {
    
    
            }
        })

Guess you like

Origin blog.csdn.net/qq_52654932/article/details/130694023