Home » vue » How to trigger modals conditionally with vue.js

How to trigger modals conditionally with vue.js

Posted by: admin November 26, 2021 Leave a comment

Questions:

i am building a food ordering app with laravel and vue.js. When a user chooses a meal to order and click the Add to cart button, there’s a call to the add-on meal model to see if there is/are add-on related to the meal chosen(there’s relationship between the 2 models), and if there is/are, a modal box pops up showing the add-ons(only if there is), else the chosen meal just gets added to the cart and user proceeds to checkout. To achieve this, I wrapped the parent modal div with a v-if like so. However, the issue is that everytime i click on the Add to cart button, the modal pops up, even when the chosen meal has no add-ons. How do I structure this to make the modal pop up only when there are related add-ons to display. My code extracts:
The trigger button(Add to cart button):

<button class="btn btn-default" @click="add_to_cart(order)" data-toggle="modal" data-target="#addon_modal"> + </button> 

My modal div:

<div v-show="addon">
  <div class="modal fade" id="addon_modal" tabindex="-1" role="dialog">
     <div class="modal-dialog"> 
        <div class="modal-content">
            <div class="modal-header">
               <h4 class="modal-title text-center">Modal title</h4>
            </div>
            <div class="modal-body">
                <p>List of add-ons here</p>
            </div>
            <div class="modal-footer">
                //buttons to add add-ons to cart and to dismiss modal here
            </div>
        </div>
      </div>
    </div>
</div>

My script:

<script>
    export default {
        data(){
            return {
                order: [],
                addon: false,
            }
        },
        methods: {
           add_to_cart(order){
               if(order.add_on.length > 0){
                   this.addon = true
               }
           }
       }
   }
</script>
Answers:

Use v-if instead of v-show will solve your problem

<div v-if="addon">
  <div class="modal fade" id="addon_modal" tabindex="-1" role="dialog">
     <div class="modal-dialog"> 
        <div class="modal-content">
            <div class="modal-header">
               <h4 class="modal-title text-center">Modal title</h4>
            </div>
            <div class="modal-body">
                <p>List of add-ons here</p>
            </div>
            <div class="modal-footer">
                //buttons to add add-ons to cart and to dismiss modal here
            </div>
        </div>
      </div>
    </div>
</div>

Demo https://jsfiddle.net/ittus/k91kcd9x/1/

If you use jquery, you can open modal programmatically