美文网首页
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入门-实现一个简陋的todolist

    Vue中通过props和$emit实现父子组件的通信。

  • 父子组件通信

    vue之父子组件间通信实例讲解(props、emit) Vue.js 递归组件实现树形菜单(实例分享)

  • vue组件通信的几种方式

    1.props/@on+$emit 用于实现父子组件通信. 2.$attrs、 $listenners(vue2....

  • 【Vue2】组件传值的六种方法

    Vue 组件之间的通信大概归类为: 父子组件通信: props/$emit;ref/refs;$attrs / $...

  • vue组件通信

    通常父子组件通信都是用props和$emit进行传递,父组件通过props传值给子组件,子组件通过$emit传值给...

  • Vue 常见 API 及问题

    组件通信 父子组件通信通过 props 和 $emit 相信小伙伴们都清楚,那么毫无关联的两个组件如果需要实现通信...

  • vue组件通信方式

    参考:vue的8种通信方式 1、$emit、props 父子组件通信(常用) 2、 ref、$refs 指向组件实...

  • Vue基础

    如何实现组件通信 父子通信 props & emit v-model sync children 兄弟通信 thi...

  • Vue父子组件通信

    父子组件通信 父组件通过设置子组件的props传递数据给子组件,子组件通过$emit发送消息给父组件。 组件及实现...

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

    emit 子组件:子组件通过$emit方法触发父组件中的parentAction事件绑定的方法 父组件父组件中绑定...

网友评论

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

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