How to fire an event when v-model changes?

jnieto picture jnieto · Oct 21, 2015 · Viewed 179.8k times · Source

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/

Answer

Stephen Hallgren picture Stephen Hallgren · Oct 23, 2015

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);
                }
            }
        }
    }
});