简体   繁体   中英

Change in Vue.js property from event only firing once

I have the following HTML:

<!DOCTYPE html>
<html>

<head>
    <script src="vue.js"></script>
</head>

<body>
    <div id="app">
        <input type="checkbox" :checked="bool" @change="checked(this)">
    </div>
    <script>
        var app = new Vue({
            el: "#app",
            data() {
                return { "bool": true }
            },
            methods: {
                checked(elem) {
                    console.log("Hey!");
                    // Cast to bool
                    this.bool = !!elem.checked;
                }
            }
        })
    </script>
</body>

I am planning on implementing some more complex behavior, so I'm not using v-model .

When I click the checkbox, the console message logs every time. However, the bool property only changes the first time I click, but not on subsequent clicks. Any idea what's going wrong?

When you try to add two !! it just removes each other and nothing happens

so you can simply say

this.bool = !this.bool

it would be like this

methods: {
  checked(elem) {
     console.log("Hey!");
     this.bool = !this.bool;
   }
}

The problem is that you are calling the event handler immediately: @change="checked(this)" . If you need to access the event do so:

template:

<div id="app">
   <input type="checkbox" :checked="bool" @change="checked('Args', $event)">
</div>

method:

methods: {
  checked(arg, event) {
    console.log(arg);
    this.bool = !!event.target.checked;
  }
}

If you don't need access to the event - you can simple use like this:

<div id="app">
   <input type="checkbox" :checked="bool" @change="bool = !bool">
</div>

Sorry, my mistake. this is not the element raising the event, it is the global window object. You can receive the element with event.target like so:

<input type="checkbox" :checked="bool" @change="checked('Hi!', $event)" id="check">
this.bool = !!event.target.checked;

https://forum.vuejs.org/t/change-in-vue-js-property-from-event-only-firing-once/88105/2

Thanks to @an_parubets for help discovering this answer!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM