如何在v模型更改时触发事件? (vue js)

[英]How to fire an event when v-model changes ? (vue js)


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...

我正在尝试使用@click启动foo()函数,但正如您所看到的,需要按两次单选按钮才能正确触发事件。只有第二次按下时才能抓住价值......

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

我想在没有@click的情况下触发事件,只在v-model(srStatus)发生变化时触发事件。

here is my Fiddle:

这是我的小提琴:

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

4 个解决方案

#1


32  

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.

此外,确保你真的想要准备好调用foo()...似乎你可能实际上并不想这样做。

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

#2


53  

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

您可以通过删除v-on指令来实现简化:

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

And use the watch method to listen for the change:

并使用watch方法来监听更改:

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

#3


9  

Vue2: if you only want to detect change on input blur (e.g. after press enter or click somewhere else) do (more info here)

Vue2:如果您只想检测输入模糊的变化(例如在按下输入或点击其他地方之后),请执行此操作(此处提供更多信息)

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

If you wanna detect single character changes (during user typing) use

如果您想检测单个字符更改(在用户输入期间)使用

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

and you can read key by define foo(event) (in JS code part) and inside it by if (event.key == "Enter") {...} or by event.keyCode more details HERE.

你可以通过定义foo(事件)(在JS代码部分中)和if(event.key ==“Enter”){...}或者event.keyCode里面的更多细节来读取密钥。

#4


7  

Just to add to the correct answer above, in Vue.JS v1.0 you can write

只是为了添加上面的正确答案,在Vue.JS v1.0中你可以写

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

So in this example it would be

所以在这个例子中它会是

 v-on:change="foo"

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


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2015/10/21/4f525293b5eef9f3d1081a6d22ae90a4.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com