Child => parent component pass parameters

Child => parent component pass parameters

The child component calls the method of the parent component
  1. Register an event for the referenced child component in the parent component (the name of this event is custom)
  2. Subcomponents can trigger this event $emit('event name')
Pass data from child component to parent component
  1. The second parameter of the $emit method can define the content passed from the child component to the parent component
  2. How to get this content in the parent component
    2.1 The method of the parent component has no custom parameters, you can get it by directly adding this parameter in the method of the parent component
    2.2 The parent component has custom parameters, you can pass in the event or get the child component the data passed. The data passed by the subcomponent can also be obtained through the event. passevent can also get the data passed by the subcomponent . Only the first parameter can be passed through event.
<body>
    <div id='app'>
        <father></father>
    </div>

    <template id="father">
        <div>
            <input type="text" name="" id="" v-model="son_val">
            <!-- 在父组件中给引用的子组件注册一个事件(这个事件的名字是自定义的) -->
            <son @son_num="son_num_1"></son>
        </div>
    </template>

    <template id="son">
        <div>
            <input type="text" v-model="num_val">
        </div>
    </template>

    <script>
        //father
        Vue.component('father', {
      
      
            template: '#father',
            data() {
      
      
                return {
      
      
                    son_val: ''
                }
            },
            methods: {
      
      
                //获取子传来的参数
                son_num_1(data) {
      
      
                    this.son_val = data
                }
            }
        })
      	//son
        Vue.component('son', {
      
      
            template: '#son',
            data() {
      
      
                return {
      
      
                    num_val: ''
                }
            },
            methods: {
      
      
            },
            updated(){
      
      
                // 子组件可以触发这个事件$emit('事件名字')
                this.$emit('son_num',this.num_val)
            }
        })

        const vm = new Vue({
      
      
            el: '#app',
            data: {
      
      },
            methods: {
      
      }
        })
    </script>
</body>

Guess you like

Origin blog.csdn.net/m0_53579196/article/details/130691602