Skip to content
Advertisement

How do I check keystroke on blur using vue?

It’s not stated clearly in vue documentation nor did I find any similar questions online so I’m asking it here.

I need a vue text input to return what the last keystroke is. The method that was tied to the blur event contains a data object so I cannot capture the default event object. I tried using custom key functions but blur always trigger before them so the execution order is wrong.

In the example below “abcdef” is the data object tied to the input control. (I removed the < > signs because the stackoverflow cannot parse it.)

<input
    type="text"
    v-model="abcdef.amount"
    @keyup.esc="cancelChange()"
    @keyup.enter="saveValue(abcdef)"
    @keyup.tab="saveValue(abcdef)"
    @focus="saveOriginalAmount(abcdef)"
    @blur="revertOriginalAmount(abcdef)">

In my vue methods

methods: {
    cancelChange(): {} //Triggers revertOriginalAmount
    saveValue(obj): {} //Save value
    saveOriginalAmount(): {} //Save the original value.
    revertOriginalAmount(): {} //Revert the value to original value
}

When the tab key is triggered, revertOriginalAmount() is immediately invoked before saveValue. Thus, the original value was saved instead of the current value. I tried setting a timeout in revertOriginalAmount to delay the saving (500ms) but it doesn’t work. Futhermore, that is only a cheap hack to fix an underlying issue which is to detect what keystrokes trigger the blur function.

So what should I pass in the parameters of @blur to get the event object?

Answer

See $event in https://v2.vuejs.org/v2/guide/events.html#Methods-in-Inline-Handlers .

@blur="revertOriginalAmount(abcdef, $event)"

$event contains the event object.

methods: {
    revertOriginalAmount(dataObject, event): {} //Revert the value to original value
}
Advertisement