vue2.0 之事件处理器

事件绑定v-on(内置事件)

<template>
  <div>
    <a v-if="isPartA">partA</a>
    <a v-else>no data</a>
    <button v-on:click="toggle">toggle</button>
    <input @keydown.enter="onkeydown">
  </div>
</template>

<script>
  export default {
    data () {
      return {
        isPartA: true
      }
    },
    methods: {
      toggle () {
        this.isPartA = !this.isPartA
      },
      onkeydown () {
        console.log('on key down')
      }
    }
  }
</script>

<style>
  html {
    height: 100%;
  }
</style>

回车,输出如下结果

备注:v-on简写为@

 

事件绑定v-on(自定义事件)

子组件hello.vue

<template>
  <div>
    {{ hello }}
    <button @click="emitMyEvent">emit</button>
  </div>
</template>

<script>
  export default {
    data () {
      return {
        hello: 'i am component hello'
      }
    },
    methods: {
      emitMyEvent () {
        this.$emit('my-event', this.hello)
      }
    }
  }
</script>

<style scoped>/**/
h1 {
  height: 100px;
}
</style>

 App,vue

<template>
  <div>
    <a v-if="isPartA">partA</a>
    <a v-else>no data</a>
    <button v-on:click="toggle">toggle</button>
    <input @keydown.enter="onkeydown">
    <comH @my-event="onComhMyEvent"></comH>
  </div>
</template>

<script>
  import comH from './components/hello.vue'
  export default {
    components: {
      comH
    },
    data () {
      return {
        isPartA: true
      }
    },
    methods: {
      toggle () {
        this.isPartA = !this.isPartA
      },
      onkeydown () {
        console.log('on key down')
      },
      onComhMyEvent (parmformA) {
        console.log('onComhMyEvent' + parmformA)
      }
    }
  }
</script>

<style>
  html {
    height: 100%;
  }
</style>

点击emit按钮,输出结果如下

1、父组件App.vue引入hello.vue子组件

2、子组件定义emitMyEvent方法,调用父组件my-event自定义事件

3、App.vue中触发onComhMyEvent方法,在控制台生成日志内容

posted @ 2017-06-26 21:47  shhnwangjian  阅读(994)  评论(0编辑  收藏  举报