如何在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