美文网首页
子组件想父组件通信

子组件想父组件通信

作者: issac_宝华 | 来源:发表于2017-08-30 03:04 被阅读0次

vue的经典案例

script标签引入vuejs中使用
<div id="counter-event-example">
  <p>{{ total }}</p>
  <v-counter v-on:counter="inscTotal"></v-counter>
</div>
<script>
// child componemt
Vue.component('button-counter', {
  template: '<button @touchstart="emitParentCounter">向父组件通信</button>',
  methods: {
    emitParentCounter() {
      this.$emit('counter')
    }
  },
})

// parent componemt
new Vue({
  el: '#counter-event-example',
  data: {
    total: 0
  },
  methods: {
    inscTotal: function () {
      this.total += 1
    }
  }
})
</script>

上面带面,看到父组件的html中v-on:counter="inscTotal"将inscTotal这方法绑定在一个自定义事件counter中,然后在子组件的script中的emitParentCounter方法,看到有这一段this.$emit('counter'),这一段就是用来触发父组件html中绑定的counter事件,一旦触发,就会调用父组件中的inscTotal方法,到此完成一个子组件想父组件通讯的行为。

子组件向父组件通信,通过在父组件的html中的子组件标签上绑定“自定义事件”监听子组件的动作,子组件则是在其script中使用 this.$emit('Event Name') 发信号给父组件,并且可以发送参数到父组件。

组件中使用
// parent component
<template>
  <div class="parent">
    <p>{{ text }}</p>
    <v-child @acceptMsg="updateMsg">
  </div>
</template>
<script>
export default {
  methods: {
    updateMsg(text){
      this.text = text
    }
  },
  data() {
    return {
      send: {
        text: 'init data...'
      }
    }
  }
}
</script>
// child component
<template>
  <div class="parent">
    <button @touchstart="sendMsg"></button>
  </div>
</template>
<script>
export default {
  methods: {
    sendMsg(){
      this.$emit('acceptMsg', 'i come from child-accept')
    }
  }
}
</script>

相关文章

  • Angular5 父子组件之间的通信

    一、父组件向子组件通信 父组件: 子组件: 二、子组件向父组件通信 父组件: 子组件:

  • 组件通信

    组件通信分为几种: 父组件给子组件通信 子组件给父组件通信 兄弟组件通信 1.父组件给子组件通信 法一...

  • ReactNative组件间的通信

    父组件向子组件通信 父组件向子组件传值 父组件向子组件传递方法 子组件向父组件通信 子组件向父组件传值 子组件向父...

  • Vue组件间通信,与服务器端通信

    组件间通信 父组件与子组件通信: props down 子组件与父组件通信:events up 若父组件要想获取子...

  • 组件间通信

    组件间通信 父组件向子组件通信,子组件之间通信 父组件以自身的state作为作为子组件的props;父组件调用se...

  • React的组件通信

    组件之间进行通信的情况: 父组件向子组件通信 子组件向父组件通信 兄弟组件之间通信 发布者-订阅者模式 一、父组件...

  • Vue中父子组件通信

    父组件向子组件通信 Pass Props 子组件向父组件通信 Emit Events

  • vue组件之间的数据传递(通信)

    种类 父组件跟子组件通信 子组件跟父组件通信 兄弟组件之间的通信 父组件如何将数据传到子组件中 可以通过prop将...

  • react之组件通信

    需要组件之进行通信的几种情况: 父组件向子组件通信 子组件向父组件通信 跨级组件通信 没有嵌套关系组件之间的通信 ...

  • React组件通信

    1.父组件与子组件通信父组件传值到子组件props。2.子组件与父组件通信父组件向子组件传一个函数,子组件将自己的...

网友评论

      本文标题:子组件想父组件通信

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