tbowden
tbowden

Reputation: 1058

Using the same component in a child and parent in Vue

I have a VueJS project - which in one view there are parent and child components that are both using the same component called deleteModal.

When I trigger the modal from the child (to show it), it triggers both the child and parent modals (except no data is passed to the modal triggered by the parent). As I understand it, this is because I have used the component twice - in the parent and child - example below. To note, it works as expected from the paren

I've researched and tried a few things: setting a key value for each of the components, changing the components ref name among other things. I have also tried using v-show to only show component just before I trigger the parent model however, this solution is not ideal.

How can I only trigger the modal from the child?

Parent Component

<template>
  <div>
    <childCompt ref="childCompt" />
    <deleteModal
      ref="deleteModal"
      @deleteTriggerAPI="deleteAPIParent"
    />
</div>
<template>

Child Component - childCompt

 <template>
      <div>
        <deleteModal
          ref="deleteModal"
          @deleteTriggerAPI="deleteAPIChild"
        />
    </div>
    <template>

Upvotes: 0

Views: 955

Answers (2)

Furman
Furman

Reputation: 29

My old answear is not good at all. I personally to show and hide element using jquery in vue. For me right now this is best solution but maybe i don't know some best.

If you want use only vue i using also variable passing to child from parent which will support visable of your modal.

We pass variable with ":" and register event with "@".

<template>
 <childComponent :isModalOpen="isModalOpen" @onModalClose="isModalOpen=false">
<template>
export default {
 name:"parent",
 data: () => {
  isModalOpen: false
 }
}

In child we catch this by using props. We need to define type of varialbe we pass. Different between props and data is that in props we cannot change value in child component.

export default {
 name: "child",
 props: {
  isModalOpen: Boolean
 }
}

And you can use this variable to show or hide modal. Also in child component we can create button to close modal and we emit event to parent in order to change variable value.

To do this we using this.$emit('eventName');

More information right here: https://forum.vuejs.org/t/passing-data-back-to-parent/1201

Upvotes: 1

user3094755
user3094755

Reputation: 1641

You could try globally defining the component,

ie, in main.js

Vue.component('deleteModal',deleteModal)

Upvotes: 0

Related Questions