组件之间的通信

自定义事件

在Vue中子组件使用$emit()来触发事件,父组件使用$on()来监听事件。
父组件也可以直接在子组件的自定义标签上使用v-on来监听子组件触发的自定义事件

<template>
  <div class="examples">
    <p class="total-count">总数<span>{{total}}</span></p>
    <my-component @increase="handleGetTotal" @reduce="handleGetTotal" @click.native="handleClick"></my-component>
  </div>
</template>
<script>
import Vue from 'vue'
Vue.component('my-component', {
  data() {
    return {
      counter: 0
    }
  },
  methods: {
    handleIncrease() {
      this.counter ++
      this.$emit('increase', this.counter)
    },
    handleReduce() {
      this.counter --
      this.$emit('reduce', this.counter)
    }
  },
  render(cr) {
    return cr(
      'div', {'class': 'child-wrap'},[
        cr('button', {attrs: {'class': 'btn'},on: {click: this.handleIncrease}},['+1']),
        cr('button', {attrs: {'class': 'btn'},on: {click: this.handleReduce}}, ['-1'])
      ]
    )
  }
})
export default {
  data() {
    return {
      total: 0
    }
  },
  methods: {
    handleGetTotal(counter) {
      this.total = counter
    },
    handleClick(ev) {
      console.log(ev)
    }
  }
}

在上面的例子中,父组件用v-on:increasev-on:reduce来监听子组件的自定义事件increasereduce,子组件使用$emit()来触发事件,其中第一个参数是自定义事件的名称,后面可选参数都是要传递的数据,可以传递多个。
使用.native修饰符表示监听原生的DOM事件。

非父子组件之间的通信

在兄弟组件,跨级组件之间通信,一般使用一个空的Vue实例来实现

<template>
  <div class="message">
    <span class="msg">{{message}}</span>
    <my-component></my-component>
  </div>
</template>
<script>
import Vue from 'vue'
let bus = new Vue()
Vue.component('my-component', {
  data() {
    return {
      msg: 'this is from child message!'
    }
  },
  methods: {
    handleEvent() {
      bus.$emit('on-message', this.msg)
    },
  },
  render(cr) {
    return cr('div',{on: {click: this.handleEvent}}, ['传递事件'])
  }
})
export default {
  data() {
    return {
      message: 'this is a placeholder'
    }
  },
  mounted() {
    let _this = this
    bus.$on('on-message', function(msg) {
      _this.message = msg
    })
  }
}
</script>

在子组件中通过自定义事件on-message传递出参数,在父组件mounted中接收,在回调中根据参数做相应的操作。
bus实例中,可以拓展其属性,添加data、methods、computed等,使其在所有页面共享


always_onerror
2 声望1 粉丝

前端小白一枚,借助平台整理学习。


下一篇 »
Vue数字输入框