pinkWojak
pinkWojak

Reputation: 281

Hiding and showing elements with v-if

I have a radio button, If the person selects "Yes" I want to render an additional div. If "Yes" was selected and then they select "No" I want to hide that div again, I tried to use v-if and a trigger with @click but it doesn't work. What did I do wrong?

<b-row>
    <b-col cols="6">
        <b-form-group>
            <label>Would you like to show the div?</label>
                <b-form-radio name="asociado" id="asociado"  @click="asociado = true">Yes</b-form-radio>
                <b-form-radio name="asociado" id="noasociado" @click="asociado=false">No</b-form-radio>
        </b-form-group>
     </b-col>
</b-row>

<b-row v-if="asociado">
    <h1>hi</h1>
</b-row>

<script>
export default {
    data(){
        return{
            asociado: false,
        }
    }
}
</script>

Upvotes: 0

Views: 865

Answers (2)

Steven B.
Steven B.

Reputation: 9362

The issue is that the creators of the b-radio-input component are not emitting a click event. If this is BootstrapVue, as suggested, you can see the events they emit here.

There's a few workarounds.

  1. Use a @change event instead

    <b-form-radio name="asociado" id="asociado"  @change="asociado = true">Yes</b-form-radio>
    <b-form-radio name="asociado" id="noasociado" @change="asociado = false">No</b-form-radio>
    
  2. Use v-model and value (I would suggest this one)

    <b-form-radio name="asociado" id="asociado" :value="true"  v-model="asociado">Yes</b-form-radio>
    <b-form-radio name="asociado" id="noasociado" :value="false" v-model="asociado">No</b-form-radio>
    
  3. Use a .native modifier on the click event.

    <b-form-radio name="asociado" id="asociado"  @click.native="asociado = true">Yes</b-form-radio>
    <b-form-radio name="asociado" id="noasociado" @click.native="asociado = false">No</b-form-radio>
    
  4. Use the b-radio-group component as @user1538301 suggested.

Upvotes: 2

gabriel.hayes
gabriel.hayes

Reputation: 2313

Assuming you're using Bootstrap-Vue (which it looks like based on your markup)

You need to use the b-radio-group component; try this markup:

<b-row>
    <b-col cols="6">
        <b-form-group>
            <label>Would you like to show the div?</label>
            <b-radio-group v-model="asociado" :options="[{text: 'Yes', value:
                true}, {text: 'No', value: false}]">
            </b-radio-group>
        </b-form-group>
    </b-col>
</b-row>

<b-row v-if="asociado">
    <h1>hi</h1>
</b-row>


Upvotes: 0

Related Questions