Daniel Santos
Daniel Santos

Reputation: 15999

How update v-model of a element that is changed programatically?

I'm using a JS plugin for Checkbox.

This plugin creates a switch button that mimics the state of the checkbox.

When the switch button is toggled its change the checked value of the checkbox.

<input type="checkbox" v-model="active" class="switch">
<script>
    var app = new Vue({
        el: '#app',
        data: {
            active: false
        }
    })
</script>

However the activedata value is only updated when the user clicks on the checkbox. Changing the checkbox checked attribute programmatically does not trigger the vue.

How can I update the vue data when the input is changed programmatically? for instance $("#myinput").prop("checked",true)

Upvotes: 6

Views: 4059

Answers (1)

acdcjunior
acdcjunior

Reputation: 135862

Vue updates the v-model's property whenever the change* event is triggered. Trigger it:

$("#myinput").prop("checked", true);
$("#myinput")[0].dispatchEvent(new Event('change')); // must trigger NATIVE event

Demo:

new Vue({
  el: '#app',
  data: {
    active: false
  }
});

$("#via-jq").click(function() {
  let currChecked = $("#myinput").prop("checked");
  $("#myinput").prop("checked", !currChecked);
  $("#myinput")[0].dispatchEvent(new Event('change'));
})
<script src="https://unpkg.com/vue"></script>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>

<div id="app">
  <input id="myinput" type="checkbox" v-model="active" class="switch"> {{ active }}
</div>

<button id="via-jq">Toggle Via jQ</button>

* This is the case for checkboxes. The event varies according to input type. E.g. input event may trigger the update for other types of elements as well.

Upvotes: 7

Related Questions