在 Vue 中,v-binding 不适用于“checked"Bootstrap 切换复选框的属性? [英] In Vue, v-binding is not working on the "checked" property for Bootstrap Toggle Checkboxes?

查看:14
本文介绍了在 Vue 中,v-binding 不适用于“checked"Bootstrap 切换复选框的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

foo.bar(布尔值)为 1 时,上面的代码行应该检查输入,当 foo.bar 为 0 时取消选中该框,但是当值为 1 时,它永远不会选中该框.

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.

当我从前一行代码中删除 data-toggle="toggle" 时,它工作得很好,但这使得显示显示为一个无聊的复选框而不是一个整洁的引导程序切换,所以这对我来说不是一个可能的解决方法.我正在使用最新版本的 bootstrap-toggle,在我的文件中包含以下代码:

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>

此外,如果我用 "1" 显式替换 "foo.bar",即使使用 data-toggle="toggle" 留在了.这让我认为 Vue 和 Bootstrap Toggle 的交互方式存在一些问题.有谁知道是什么导致了这个错误?

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?

推荐答案

在这种情况下,您需要手动处理.

You need to manually handle things in that case.

首先,您需要通过在其中添加一个 ref 属性来获取对复选框元素的引用:

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')
    }
},

为了保持数据双向同步,您需要在 mounted 回调函数中添加一个 change 事件侦听器,该函数检测是否单击了切换按钮然后更新相应地 foo.bar 的值.

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

查看这个 JS Fiddle 以获得完整的演示:https://jsfiddle.net/eywraw8t/169950/

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

这篇关于在 Vue 中,v-binding 不适用于“checked"Bootstrap 切换复选框的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆