Search code examples
javascriptvue.jsbootstrap-vue

Vuejs: Change a boolean variable based on if a radio button is checked or not


I need to show a div based on a condition, v-if="addNewCard". Only if it is true i need to show the div. Intially setting the value of addNewCard as false. When the user clicks the radio button - Add new card, I need to make it true so that the div is shown, but if the user clicks the other radio button the variable should be made false hiding the div. How can I achieve this. It would be nice f it could work without a need to call a function on click.

            addNewCard: false

            <div>
                <b-form-group label="Payment Options">
                    <b-form-radio v-model="selected" name="some-radios" value="A">Continue payment using the card **** **** ****</b-form-radio>
                    <b-form-radio v-model="selected" name="some-radios" value="B">Add new Card</b-form-radio>
                </b-form-group>
            </div>
            <div v-if="addNewCard">
                  ............  
            </div>

Solution

  • use a computed method here:

    computed: {
      addNewCard: {
        get: function () {
          return this.selected === 'A'
        }
      }
    }
    

    Now your addNewCard is true if the value is A and false when the value is B.

    You can read more about computed properties here