Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fire an event when v-model changes?

I'm trying to fire the foo() function with the @click but as you can see, need press the radio button two times to fire the event correctly . Only catch the value the second time that you press...

I want to fire the event without @click only fire the event when v-model (srStatus) changes.

here is my Fiddle:

http://fiddle.jshell.net/wanxe/vsa46bw8/

like image 643
jnieto Avatar asked Oct 21 '15 10:10

jnieto


People also ask

Is V-model two-way binding?

The v-model directive makes two-way binding between a form input and app state very easy to implement. One can bind a form input element and make it change the Vue data property when the content of the field changes.

Can you have multiple V models?

With the release of Vue 3 now we can add multiple v-model for two-way data binding in a more standardized way on the same component with more flexibility. As given in Vue 3 document the syntax of using v-model on a custom component is similar by-passing modelValue as a prop and emitting an update:modelValue event.

How do I pass a Vue event?

To pass event and argument to v-on in Vue. js, we can call the event handler method with $event and whatever argument. And then we can retrieve the arguments from the method parameters in the same order. to call addToCart with the $event object and the ticket.id property.

What is V-on change in Vue?

Jul 5, 2019. In Vue, the v-on directive is how you run JavaScript in response to DOM events. If you want to run some code when the user clicks a button, you should use v-on .


2 Answers

You can actually simplify this by removing the v-on directives:

<input type="radio" name="optionsRadios" id="optionsRadios1" value="1" v-model="srStatus"> 

And use the watch method to listen for the change:

new Vue ({     el: "#app",     data: {         cases: [             { name: 'case A', status: '1' },             { name: 'case B', status: '0' },             { name: 'case C', status: '1' }         ],         activeCases: [],         srStatus: ''     },     watch: {         srStatus: function(val, oldVal) {             for (var i = 0; i < this.cases.length; i++) {                 if (this.cases[i].status == val) {                     this.activeCases.push(this.cases[i]);                     alert("Fired! " + val);                 }             }         }     } }); 
like image 95
Stephen Hallgren Avatar answered Nov 15 '22 23:11

Stephen Hallgren


This happens because your click handler fires before the value of the radio button changes. You need to listen to the change event instead:

<input    type="radio"    name="optionsRadios"    id="optionsRadios2"    value=""   v-model="srStatus"    v-on:change="foo"> //here 

Also, make sure you really want to call foo() on ready... seems like maybe you don't actually want to do that.

ready:function(){     foo(); }, 
like image 31
pherris Avatar answered Nov 16 '22 00:11

pherris