子=>父 组件传参

子=>父 组件传参

子组件调用父组件的方法
  1. 在父组件中给引用的子组件注册一个事件(这个事件的名字是自定义的)
  2. 子组件可以触发这个事件$emit(‘事件名字’)
子组件给父组件传递数据
  1. $emit方法第二个参数可以定义子组件给父组件传递的内容
  2. 在父组件中怎么拿到这内容
    2.1 父组件这个方法没有自定参数,在父组件的方法直接加这个参数就可以拿到
    2.2 父组件有自定义参数,可以传入 e v e n t 也可以拿到子组件传递的数据。通过 event也可以拿到子组件传递的数据。通过 event也可以拿到子组件传递的数据。通过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>

猜你喜欢

转载自blog.csdn.net/m0_53579196/article/details/130691602