I am using the bootstrap-vue package and have a checkbox as follows:
<b-form-checkbox v-model="isSelected"switch></b-form-checkbox>
i have data property
data(){
isSelected: false
}
what i would like to do is for user to click the checkbox and before the checked value is changed is to perform some sort of validation by calling a method. The method may then prevent the value being changed.
How can i do this?
I have tried to bind method to the @change event but then when i try to set this.isSelected = false
the checkbox value is still checked.
b-form-checkbox
has internal state for whether or not it is checked. It does get synced with the prop but it's via a watch
so it'll only update when the prop value changes. In your case you're trying to prevent it changing, so the watch
won't trigger.
You may want to consider disabling the checkbox instead.
To get this to work without disabling the checkbox you'd need to ensure the checkbox's watch
gets triggered. For that we need to let the original change happen, allow it to update the prop, then change it back to the value we want.
The example below uses async
/await
but you could do it using a callback passed to $nextTick
if you prefer.
new Vue({
el: '#app',
data () {
return {
isSelected: false
}
},
methods: {
async onInput () {
await this.$nextTick()
this.isSelected = false
}
}
})
<link type="text/css" rel="stylesheet" href="https://unpkg.com/bootstrap@4.3.1/dist/css/bootstrap.css" />
<link type="text/css" rel="stylesheet" href="https://unpkg.com/bootstrap-vue@2.0.0-rc.27/dist/bootstrap-vue.css" />
<script src="https://unpkg.com/vue@2.6.10/dist/vue.js"></script>
<script src="https://unpkg.com/bootstrap-vue@2.0.0-rc.27/dist/bootstrap-vue.js"></script>
<div id="app">
<b-form-checkbox v-model="isSelected" @input="onInput"></b-form-checkbox>
</div>
I've used the input
event but change
would work too.