eventHook Vue 事件绑定hook

2020-04-09 11:47:37 浏览数 (1)

tt.gif

使用例子
代码语言:javascript复制
<template>
  <div class="home">

    <div>
      <div style='margin: 20% auto; width: 600px' title=''>

        <Client title='client one' v-bind='clientOne' />
        <Client title='client two' v-bind='clientTwo' />
      
      </div>
    </div>
    
  </div>
</template>

<script>
import { ref } from '@vue/composition-api'
import { vmEventHook } from '@/hooks/eventHook'


const Client = {
  
  props: [ 'title', 'receive', 'send' ],

  setup(props){

    const msg = ref('')
    props.receive(data => msg.value = data)
    return {
      msg,
    }

  },

 
  render(){
    const { title, msg, send } = this

    return (
      <Card style='margin-bottom: 40px' title={ title }>
        <p> { msg } </p>
        <Input onInput={send} />
      </Card>
    )
    
  }
  
}


export default { 

  components:{
    Client,
  },
  
  setup(_, context){

    const clientOneEventTag = 'toOne' 
    const clientTwoEventTag = 'toTwo'
    const vm = context.root

    const clientOne = ref({
      receive: handler => vmEventHook(clientOneEventTag, handler, vm),
      send: msg => vm.$emit(clientTwoEventTag, msg)
    })

    const clientTwo = ref({
      receive: handler => vmEventHook( clientTwoEventTag, handler, vm),
      send: msg => vm.$emit(clientOneEventTag, msg)
    })
    

    return {
      clientOne,
      clientTwo
    }
    

  }

}
</script>
实现
代码语言:javascript复制
/**
 * dom 事件绑定
 * @param { String } name 事件名称 
 * @param { Function } handler 回调函数
 * @param { Element } target 绑定对象
 * @param { Object } option 配置属性
 * @returns { Function } remove 事件移除函数
 */
export function eleEventHook( name, handler, target, option ){

    if(!handler) return
    if(!target) return

    const addEvent = target.addEventListener || target.on
    const removeEvent = target.removeEventListener || target.off
    const remove = () => removeEvent.call(target, name, handler, option)
    addEvent.call(target, name, handler, Option)

    return remove
}

/**
 * vm 事件绑定
 * @param { String } name 事件名称 
 * @param { Function } handler 回调函数
 * @param { vm } vm 绑定vue实例
 * @param { Object } option 配置属性
 * @returns { Function } remove 事件移除函数
 * @exports
 * 
 * const vm = new Vue({...})
 * // 绑定事件,并返回移除函数
 * const removeTime = vmEventHook('time', () => console.log(new Date()), vm)
 *  
 */
export function vmEventHook (name, handler, vm, option){

    if(!handler)return
    if(!vm) return

    vm.$on(name, handler, option)
    const remove = () => vm.$off(name)
    return remove

}
gif

0 人点赞