vue2.0 之事件處理器
阿新 • • 發佈:2017-06-27
alt data sof rom 簡寫 temp mic emit 處理器
事件綁定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方法,在控制臺生成日誌內容
vue2.0 之事件處理器