子组件想父组件通信

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>
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容