Ari Fordsham
Ari Fordsham

Reputation: 2515

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?

Upvotes: 2

Views: 1524

Answers (3)

Ari Fordsham
Ari Fordsham

Reputation: 2515

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!

Upvotes: 2

an_parubets
an_parubets

Reputation: 656

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>

Upvotes: 0

Joseph
Joseph

Reputation: 6259

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

Upvotes: 1

Related Questions