Reputation: 19705
I deal with a boostrap switch
In JQuery, it is easy, you can do as doc state:
$('input[name="my-checkbox"]').on('switchChange.bootstrapSwitch', function(event, state) {
console.log(this); // DOM element
console.log(event); // jQuery event
console.log(state); // true | false
});
But in VueJS, I can't bind the element to value:
<div id="vue-instance">
<input type="checkbox" name="my-checkbox" checked @click="log">
</div>
var vm = new Vue({
el: '#vue-instance',
data: {
},
methods:{
log(){
alert('ok');
}
},
mounted(){
$("[name='my-checkbox']").bootstrapSwitch();
}
});
Here is the fiddle: https://jsfiddle.net/xoco70/tfkLkLqw/1/
Upvotes: 0
Views: 1737
Reputation: 2778
If you really need to use this, you can simply bind to the change on the mounted
life-cycle hook.
var vm = new Vue({
el: '#vue-instance',
data: {
},
methods:{
log(event, state){
alert('ok');
}
},
mounted(){
$("[name='my-checkbox']").bootstrapSwitch();
$('input[name="my-checkbox"]').on('switchChange.bootstrapSwitch', this.log.bind(this));
}
});
I say If you really need to use this because you are mixing the data driven approach of Vue.js
with querying the view with JQuery
. I also tried coming up with a solution where you could use a Vue
binding so you could react to events or changes in the model, but it seems the library does not update the value of the html input when the toggle is switched.
Working Example
var vm = new Vue({
el: '#vue-instance',
data: {
bSwitch: null
},
methods:{
log(event, state){
this.bSwitch = state;
console.log('switch to state ' + state );
}
},
mounted(){
$("[name='my-checkbox']").bootstrapSwitch();
$('input[name="my-checkbox"]').on('switchChange.bootstrapSwitch', this.log.bind(this));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://unpkg.com/[email protected]/dist/js/bootstrap-switch.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.4/vue.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet"/>
<link href="https://unpkg.com/[email protected]/dist/css/bootstrap3/bootstrap-switch.css" rel="stylesheet"/>
<div id="vue-instance">
Switch State: {{bSwitch}}
<br>
<input type="checkbox" name="my-checkbox">
</div>
Upvotes: 1