Vue:v-on自定义事件
Vue中父组件使用prop向子组件传递数据,那么子组件向父组件使用什么方式传递信息:自定义事件。
1.先来看官网上面教程
每个 Vue 实例都实现了事件接口,即:
- 使用 
$on(eventName)监听事件 - 使用 
$emit(eventName, optionalPayload)触发事件 
<div id="counter-event-example">
  <p>{{ total }}</p>
  <button-counter v-on:increment="incrementTotal"></button-counter>
  <button-counter v-on:increment="incrementTotal"></button-counter>
</div>
Vue.component('button-counter', {
  template: '<button v-on:click="incrementCounter">{{ counter }}</button>',
  data: function () {
    return {
      counter: 0
    }
  },
  methods: {
    incrementCounter: function () {
      this.counter += 1
      this.$emit('increment')
    }
  },
})
new Vue({
  el: '#counter-event-example',
  data: {
    total: 0
  },
  methods: {
    incrementTotal: function () {
      this.total += 1
    }
  }
})
2.功能解释:
当子组件click出发一个效果,子组件事件(incrementTotal)命名为"increment"放入父组件中触发($emit('increment'))。
以下为个人理解:子组件的事件(incrementTotal)是独立不可共享的,使用事件绑定(v-on)给子组件事件包装一层可以被父组件接收的外衣,
实际上父组件还是要使用子组件事件(incrementTotal),当然其内部逻辑可自定义。
以上内容为个人学习所感,如有错误请指正,勿喷。
                    
                
                
            
        
浙公网安备 33010602011771号