[Vuejs]-Show Component on Click with vue JS

3👍

For example. Create modal with your component inside (i use bootstrap-vue)

 <b-modal ref="my-component" >
     <your-component></your-component>
 </b-modal>

And add event to @click method

this.$refs.my-component.show();

2👍

Usually you want to use a Bool to control whether a modal is visible or not.
Simply use @click (v-on:click) to toggle Bool.

In Data:

modal: false

Then on a button:

<button @click="modal = !modal">Click me to toggle modal</button>

Edit: Forgot to add logic on modal:

<modal v-model="modal"></modal>

The v-model simply means that it doesn’t show if it’s false and it does if it’s true.

More info: https://v2.vuejs.org/v2/api/#v-model

I hope this is sufficient.

Piece of advice: Next time give a better explanation with more code.
Otherwise it will become guesswork for everyone who wants to answer.

1👍

The question seem to have an extra logic, since you have multiple cards with different items, you want to open a modal with a single item info each time, and probably you don’t want to create N modals for all the records displayer in cards.

As the previous answers state, you CAN open a modal by calling a method, and also you can open a modal replacing a variable value that allows it, but also you need to close the modal and that is an extra logic you must have in mind.

you can have an event directive as you have here, and also your modal code (component most of the times):

<div class="card" @click="showDetails()">

<my-modal-component v-show="openModal" >
   <my-card-information-component />
</my-modal-component>

on your script you must declare the property that will trigger the moday display and the method to mutate the property

export default {
    data(){
        return {
           showModal:false
        }
    },
    methods:{
       showDetails(){
           this.showModal = true;
       }
    }
}

to close the modal you have multiple options, you can add a button to the component, click the modal backdrop, etc. But to achieve this you need to emit an event from the child component to the parent component that will update the showModal property back to false and will close the modal.

1👍

Here is what worked for me.

Please note, my answer is in Vue3 as of Feb 17, 2022

<script setup>
  // set a boolean ref value as false. we will be using the openModal function to trigger its change
  let showModal = ref(false);

  // create the openModal function and set showModal to true
  const openModal = () => {
    showModal.value = true;
    // console.log(showModal);
  };
</script>  

<template>
  // Here is our modal. It will only display on the page once we click the button that triggers the openModal function
    <Modal v-if="showModal" />
  
  // Here is the button that triggers the openModal function, changing the showModal boolean value to true
    <button v-on:click="reply" type="button">Reply</button>
</template>

Leave a comment