Search code examples
vue.jsevent-handlingconditional-statementsevent-binding

Vue conditional event binding with arguments


I try to bind coditionaly an event method like

the template

 <div class="survey-card__option radio" :class="data.column ? data.column : ''"
                     v-for='(option, index) in data.options' :key="index">
                    <input type="radio" :name="form[data.id + '--' + fieldKey]"
                           :value="option.body"
                           :id="option.body"
                           v-on="{ change: data.hasButton ? watchChange(data, $event) : null }"
                           v-model="form[data.id + '--' + fieldKey]">&nbsp;
                    <label :for="option.body" class="survey-card__options__label">
                        <span>{{ option.body }}</span>
                    </label>
                </div>

the listener

v-on="{ change: data.hasButton ? watchChange(data, $event) : null }"

and the method

watchChange(data, event) {
            console.log(event)//undefined
            console.log(data)
        }

I try to track the current value of the checked and match against json value and in case show some text.

The method will fire but I can't track the $event I get the following error

[Vue warn]: Property or method "$event" is not defined on the instance but referenced during render

Solution

  • You actually have to define the the $event argument by yourself (use a arrow function for example):

    v-on="{ change: data.hasButton ? ($event) => watchChange(data, $event) : null }"