gitbrent / bootstrap4-toggle

Bootstrap 4 Switch Button / Toggle
https://gitbrent.github.io/bootstrap4-toggle/
MIT License
213 stars 67 forks source link

None of Vue directives work #68

Open nikriaz opened 1 year ago

nikriaz commented 1 year ago

Surprisingly, even though events and checked state are propagated to the html, none of Vue directives work. For example:

<input type="checkbox" data-toggle="toggle" id="checkbox" v-on:change="toggleChecked"> -> this doesn't work. <input type="checkbox" data-toggle="toggle" id="checkbox" onchange="toggleChecked()> - > though this works. v-model doesn't work as well, seems because it relies on the same event mechanism.

Why?

nikriaz commented 1 year ago

Ok, wrote a component for Vue 2.x. Use it like this: <toggle id="checkbox" data-on="Enabled" data-off="Disabled" v-model="toggleChecked" /> Based on the original Vue wrapper for Select2 from here

Vue.component("toggle", {
    props: ["id", "value", "disabled", "data-on", "data-off", "data-onstyle", "data-offstyle"],
    template: "<input type='checkbox'><slot></slot></input>",
    mounted: function () {
        var vm = this;
        $(this.$el)
            .attr("id", this.id)
            .bootstrapToggle({
                on: this.dataOn,
                off: this.dataOff,
                onstyle: this.dataOnstyle,
                offstyle: this.dataOffstyle,
            })
            .bootstrapToggle(this.value ? "on" : "off")
            .change(function () {
                vm.$emit("input", $(this).prop("checked"));
            });
    },
    watch: {
        value: function (value) {
            $(this.$el).bootstrapToggle(value ? "on" : "off")
        },
        disabled: function (disabled) {
            $(this.$el).bootstrapToggle(disabled ? "disable" : "enable")
        }
    },
    destroyed: function () {
        $(this.$el).bootstrapToggle("destroy");
    }
});