How to trigger an onchange event?

Will the directive v-model bind an onchage event on the HTML element?
How to trigger an onchange event?
like this:

<input type="text" v-model="userName">

Do I need to bind event listener manually? Or I can use the “watch” to monitor the “userName”?
Which one is better?

2 Likes

If you want v-model to update on change instead of on input you can add a lazy modifier:

v-mode.lazy="userName"

Or if you wanted to do some other logic when the change event occurs you can just add a change handler:

<input v-model="userName" @change="someHandler">
1 Like

I am pretty sure you misunderstood the question.
merlin was asking if Vue would generate native DOM events after input value is changed through the v-model binding.

<form onchange="console.log('changed!')">
  <input type="text" v-model="userName">
</form>

..... somewhere in Vue instance code
this.userName = "John"; /// <--- how to make this trigger native bubbling DOM Event that could be intercepted by outer listeners, for example.

Maybe using watch in the component ?

watch {
    value(value) {
        this.$emit('onchange', value);
        // or generate/simulate a native events (not sure how, but its outside Vue's realm I think
    }
}
1 Like

Just to be clear:

In a component, you can have an input in your component template like this:

<input type="file" :id="inputName" :name="inputName"  v-on:change="signalChange" />

Then in the component methods you can have a handler

methods:{
     signalChange: function(evt){
                   this.$emit("change", evt);

I am having success with oninput method which appears to be supported by all major browsers.

<input v-on:input="myChangeFunction(whatever)" type="text" />

Use this method for textareas also.

Use onchange still for dropdowns

2 Likes

@sfullman thanks man.

Hello,

I used watch and lazy…

try this:

<input v-model.lazy="search"
           placeholder="Search for..." />

       data: function () {
            return {
                search: ''
            };
        },
        watch: {
            search: function (value) {
                console.log(value);
            }
        }

This is unnecessary, you can simply bind a change event as well as use the .lazy modifier. https://jsfiddle.net/jamesbrndwgn/eywraw8t/507779/

sfullman is correct, as the VueJS documentation currently says ‘text and textarea elements use value property and input event’.
The current shorthand approach would be:
<input type=“text” v-model=“userName” @input=“myChangeFunction(whatever)” />