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

╄→гoц情女王★ 提交于 2021-01-28 14:20:42

问题


<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?


回答1:


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/



来源:https://stackoverflow.com/questions/51315860/in-vue-v-binding-is-not-working-on-the-checked-property-for-bootstrap-toggle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!