Búsqueda de sitios web

javascript - ¿Cómo disparar un evento cuando cambia v-model?


Estoy intentando ejecutar la función foo() con el @click, pero como puedes ver, necesitas presionar el botón de opción dos veces para que el evento se ejecute correctamente. Solo captura el valor la segunda vez que presionas...

Quiero disparar el evento sin @click, solo disparar el evento cuando v-model (srStatus) cambie.

aquí está mi Fiddle:

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

Respuesta #1

De hecho, puedes simplificar esto eliminando las directivas v-on:

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

Y utiliza el método watch para escuchar el cambio:

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

Respuesta #2

Esto sucede porque tu manejador click se ejecuta antes de que cambie el valor del botón de opción. Necesitas escuchar el evento change en su lugar:

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

Además, asegúrate de que realmente quieres llamar a foo() cuando esté listo... parece que tal vez en realidad no quieras hacer eso.

ready:function(){
    foo();
},

Respuesta #3

Deberías usar @input:

<input @input="handleInput" />

@input se dispara cuando el usuario cambia el valor de entrada.

@change se activa cuando el usuario cambia el valor y pierde el foco del campo de entrada (por ejemplo, hace clic en algún lugar fuera)

Puedes ver la diferencia aquí: https://jsfiddle.net/posva/oqe9e8pb/

Respuesta #4

Vue2: si solo quieres detectar cambios cuando el input pierde el foco (por ejemplo, después de presionar enter o hacer clic en otro lugar) haz (más información aquí)

<input @change="foo" v-model... >

Si quieres detectar cambios de un solo carácter (durante la escritura del usuario) usa

<input @keydown="foo" v-model... >

También puedes usar los eventos @keyup y @input. Si quieres pasar parámetros adicionales úsalo en la plantilla, por ejemplo, @keyDown="foo($event, param1, param2)". Comparación abajo (versión editable aquí)

new Vue({
  el: "#app",
  data: { 
    keyDown: { key:null, val: null,  model: null, modelCopy: null },
    keyUp: { key:null, val: null,  model: null, modelCopy: null },
    change: { val: null,  model: null, modelCopy: null },
    input: { val: null,  model: null, modelCopy: null },
    
    
  },
  methods: {
  
    keyDownFun: function(event){                   // type of event: KeyboardEvent   
      console.log(event);  
      this.keyDown.key = event.key;                // or event.keyCode
      this.keyDown.val = event.target.value;       // html current input value
      this.keyDown.modelCopy = this.keyDown.model; // copy of model value at the moment on event handling
    },
    
    keyUpFun: function(event){                     // type of event: KeyboardEvent
      console.log(event);  
      this.keyUp.key = event.key;                  // or event.keyCode
      this.keyUp.val = event.target.value;         // html current input value
      this.keyUp.modelCopy = this.keyUp.model;     // copy of model value at the moment on event handling
    },
    
    changeFun: function(event) {                   // type of event: Event
      console.log(event);
      this.change.val = event.target.value;        // html current input value
      this.change.modelCopy = this.change.model;   // copy of model value at the moment on event handling
    },
    
    inputFun: function(event) {                    // type of event: Event
      console.log(event);
      this.input.val = event.target.value;         // html current input value
      this.input.modelCopy = this.input.model;     // copy of model value at the moment on event handling
    }
  }
})
div {
  margin-top: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

Type in fields below (to see events details open browser console)

<div id="app">
  <div><input type="text" @keyDown="keyDownFun" v-model="keyDown.model"><br> @keyDown (note: model is different than value and modelCopy)<br> key:{{keyDown.key}}<br> value: {{ keyDown.val }}<br> modelCopy: {{keyDown.modelCopy}}<br> model: {{keyDown.model}}</div>
  
  <div><input type="text" @keyUp="keyUpFun" v-model="keyUp.model"><br> @keyUp (note: model change value before event occure) <br> key:{{keyUp.key}}<br> value: {{ keyUp.val }}<br> modelCopy: {{keyUp.modelCopy}}<br> model: {{keyUp.model}}</div>
  
  <div><input type="text" @change="changeFun" v-model="change.model"><br> @change (occures on enter key or focus change (tab, outside mouse click) etc.)<br> value: {{ change.val }}<br> modelCopy: {{change.modelCopy}}<br> model: {{change.model}}</div>
  
  <div><input type="text" @input="inputFun" v-model="input.model"><br> @input<br> value: {{ input.val }}<br> modelCopy: {{input.modelCopy}}<br> model: {{input.model}}</div>
     
</div>

Respuesta #5

Solo para agregar a la respuesta correcta anterior, en Vue.JS v1.0 puedes escribir

<a v-on:click="doSomething">

Entonces, en este ejemplo sería

 v-on:change="foo"

Ver: http://v1.vuejs.org/guide/syntax.html#Arguments

Artículos relacionados