[Vuejs]-VueJS2 – Triggering modal component from another component

0👍

One way of doing this would be to simply add a property to the modal component e.g helpData and pass the relevant data to this prop in each of the main pages as shown below

Modal.vue

<template>
    <div class="modal" v-if="open">
        <div class="modal-title">
            <h4>Help</h4>
        </div>
    </div>
</template>

<script>

export default {
    name: 'Modal',

    props: {
        open: {
            type: Boolean,
            default: false,
        },
        helpData: {
            type: String,
            required: true
        }
    },

    methods: {
        close() {
            this.$emit('closed');
        },
    },
};
</script>

Home.vue

<template>
  <div>
    Home
    <modal
      :open="helpOpen"
      @closed="openHelpModal"
      :help-data="This is a sample help data for the home view"
    />
  </div>
  <template>
    <sidebar @help-modal="helpOpen = true"/>
  </template>
</template>
<script>
import Sidebar from '@/components/Sidebar.vue';
export default {
  name: 'Home',
  components: {
    Sidebar,
  },
 data() {
   return {
     helpOpen: false,
  }
 }
 methods: {
   openHelpModal() {
     this.helpOpen = !this.helpOpen;
   },
 }
}
</script>

As indicated by @ljubadr, I have included the logic that would open the modal in the sidebar component of Home.vue. Also, I would recommend you change the name of the function openHelpModal to closeHelpModal (seeing as this function will basically close the modal) or toggleHelpModal (since from the logic of the function, it toggles the modal state).

Leave a comment