Kyle Somers
Kyle Somers

Reputation: 632

In Vue, v-binding is not working on the "checked" property for Bootstrap Toggle Checkboxes?

<input type="checkbox" data-toggle="toggle" id="id2" :checked="foo.bar">

The line of code above should check the input when foo.bar (which is a boolean) is 1 and uncheck the box when foo.bar is 0, but it never checks the box when the value is 1.

When I remove the data-toggle="toggle" from the previous line of code, it works perfectly, but that makes the display show as a boring checkbox instead of a neat bootstrap toggle, so that isn't a possible workaround for me. I'm using the most recent version of bootstrap-toggle, with this code in my file:

<link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">
<script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>

Also if I replace "foo.bar" explicitly with "1", that will check the box, even with the data-toggle="toggle" left in. This leads me to think that it is some issue with how Vue and Bootstrap Toggle are interacting. Does anyone know what is causing this bug?

Upvotes: 2

Views: 5954

Answers (1)

Julian Paolo Dayag
Julian Paolo Dayag

Reputation: 3729

You need to manually handle things in that case.

First, you need to get a reference to the checkbox element by adding a ref attribute into it:

<input type="checkbox" ref="checkbox" :checked.prop="foo.bar">

Then you would need to create a watcher which manually updates the value of the toggle plugin:

watch: {
    'foo.bar': function(enabled) {
        $(this.$refs.checkbox).bootstrapToggle(enabled ? 'on' : 'off')
    }
},

And to keep the data two-way synced, you need to add a change event listener into the mounted callback function which detects if the toggle is clicked and then update the value of the foo.bar accordingly.

mounted: function() {
      $(this.$refs.checkbox).bootstrapToggle().change(function(e) {
        this.foo.bar = $(e.target).prop('checked');
      }.bind(this));
},

See this JS Fiddle for a complete demo: https://jsfiddle.net/eywraw8t/169950/

Upvotes: 2

Related Questions