2017-02-19 67 views
12

我有以下Vue的事件處理程序與CONTENTEDITABLE:Vue的結合事件處理程序

<div contentEditable="true" 
v-on:keyup="changed($event, current, 0)" 
v-on:paste="changed($event, current, 0)" 
v-on:blur="changed($event, current, 0)" 
v-on:delete="changed($event, current, 0)" 
v-on:focused="changed($event, current, 0)"></div> 

不過,我有很多地方我所說的相同的代碼和代碼越來越長,冗長。有沒有辦法結合事件處理程序?例如:

v-on:keyup:paste:blur:delete:focused

回答

1

我不認爲目前有一種方法可以像您所描述的那樣組合事件監聽器。

你可以做的是使該div它自己的包裝組件(命名爲「編輯 - 包裝」,例如),併發出一個change事件:

<div 
    contentEditable="true" 
    v-on:keyup="$emit('change', {$event, current})" 
    v-on:paste="$emit('change', {$event, current})" 
    v-on:blur="$emit('change', {$event, current})" 
    v-on:delete="$emit('change', {$event, current})" 
    v-on:focused="$emit('change', {$event, current})"> 
</div> 

然後你只需要聽一個在組件上變化事件(data$event一個對象,current屬性):

<editable-wrapper @change="changed(data)"></editable-wrapper> 
3

您可以創建自定義指令用於這一目的。本示例可能會對您有所幫助:

Vue.directive('wrap-on', { 
    bind: function(el, binding, vnode) { 
    // Keep function to remove the event later. 
    el.wrappedEventFunctions = el.wrappedEventFunctions || {}; 
    el.wrappedEventFunctions[binding.rawName] = binding.value; 

    for (var key in binding.modifiers) { 
     // Check if element is a vue component 
     if (vnode.componentInstance) { 
     vnode.componentInstance.$on(key, binding.value); 
     } else { 
     el.addEventListener(key, binding.value); 
     } 
    } 
    }, 
    unbind: function(el, binding, vnode) { 
    for (var key in binding.modifiers) { 
     if (vnode.componentInstance) { 
     vnode.componentInstance.$off(key, el.wrappedEventFunctions[binding.rawName]); 
     } else { 
     el.removeEventListener(key, el.wrappedEventFunctions[binding.rawName]); 
     } 
    } 
    } 
}) 

此指令將向該元素添加事件處理程序。它檢查元素是否是vue組件;如果它是vue組件,則它通過$on註冊事件。如果它不是一個vue組件,它使用addEventListener。如果你願意,你可以改變這種行爲。

和使用是這樣的:

<input v-wrap-on.click.keydown="mixedCallback" /> 

或者:

<some-custom-component v-wrap-on.click.keydown="mixedCallback"> 
    ... 
</some-custom-component> 
+0

有了這個解決方案$事件是不可用 – user3743266