美文网首页
vue父子组件通过props和emit实现通信

vue父子组件通过props和emit实现通信

作者: 手指乐 | 来源:发表于2019-10-15 16:17 被阅读0次

    emit

    • 子组件:
      子组件通过$emit方法触发父组件中的parentAction事件绑定的方法
    <template>
        <div @click="onChildAction">i am test component</div>
    </template>
    
    <script>
    export default {
        methods:{
            onChildAction(){
                 this.$emit('parentAction')
            }
        }
         
    }
    </script>
    
    • 父组件
      父组件中绑定一个parentAction事件
    <template>
        <div id = "mutil">
            <TestComponent v-on:parentAction="onParentAction"></TestComponent>
        </div>
        
    </template>
    
    <script>
    import TestComponent from './commoncomponent/TestComponent'
    export default {
        components:{TestComponent},
        methods: {
            onParentAction(){
                alert("onParentAction")
            }
        }
    }
    </script>
    
    • 还可以带参数:
    onChildAction(){
                 this.$emit('parentAction',{"showA":"A","showB":"B"})
            }
    
    methods: {
            onParentAction(e){
                alert(e.showA)
            }
        }
    

    props

    • 在子组件中定义props
    <template>
        <div @click="onChildAction">{{msgFromParent}}</div>
    </template>
    
    <script>
    export default {
        props:{
          msgFromParent:{
             type:String
          }
        },
        methods:{
            onChildAction(){
                 this.$emit('parentAction',{"showA":"A","showB":"B"})
            }
        }
         
    }
    </script>
    
    • 在父组件中使用子组件时,绑定子组件的props:
      自组价中点击div,触发父组件的onParentAction方法,onParentAction改变父组件的msg属性,由于子组件的msgFromParent绑定了父组件的msg,子组件中的显示会同步改变
    <template>
        <div id = "mutil">
            <TestComponent v-on:parentAction="onParentAction" :msgFromParent="msg"></TestComponent>
        </div>
        
    </template>
    
    <script>
    import TestComponent from './commoncomponent/TestComponent'
    export default {
        data(){
            return {
                 msg:"parent1"
            }
           
        },
        components:{TestComponent},
        methods: {
            onParentAction(e){
                this.msg = "parent2"
            }
        }
    }
    </script>
    

    相关文章

      网友评论

          本文标题:vue父子组件通过props和emit实现通信

          本文链接:https://www.haomeiwen.com/subject/mmmsmctx.html