How to properly add conditional event binding in Vue.js?

Total
12
Shares

Using Vue.js and I am trying to add a conditional event handler to the keydown event on an <input>. I want to avoid adding the click handler at all if the condition is not met. I followed Evan You’s suggestion: https://github.com/vuejs/vue/issues/7349#issuecomment-354937350

I’m getting an error saying Cannot read property '_wrapper' of null for the following:

<input v-on: {
  keydown: fieldData.fixedLength ? inputEnforceMaxlength : null,
}>

I also tried passing an empty object but got a different error saying: handler.apply is not a function for the following:

<input v-on: {
  keydown: fieldData.fixedLength ? inputEnforceMaxlength : {},
}>

Is this the proper way to add conditional event handlers or are there are other alternatives? Thanks!


Solution

You should be able to do something like this…

<input v-on="fieldData.fixedLength ? { keydown: inputEnforceMaxlength } : null">

Or you can just use a render() function instead of a <template>

Using a render function

render(h) {
    const data = {
        on: {
            blur: this.validate,
            focus: this.showLabel,
        },
    };

    if (this.fieldData.fixedLength) {
        data.on.keydown = this.inputEnforceMaxlength;
    }

    if (this.fieldName === 'Phone') {
        data.on.keypress = this.inputMaskTel;
    }

    return h('input', data);
}
Leave a Reply

Your email address will not be published. Required fields are marked *