5

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.

2 Answers 2

8

I finally achieved it using @click.native.prevent

Sign up to request clarification or add additional context in comments.

Comments

4

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/[email protected]/dist/css/bootstrap.css" />
<link type="text/css" rel="stylesheet" href="https://unpkg.com/[email protected]/dist/bootstrap-vue.css" />

<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<script src="https://unpkg.com/[email protected]/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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.