Utilizing a shared component in both a child and parent within a Vue application

I am currently working on a VueJS project, where I have parent and child components within one view. Both components are using the same component called deleteModal.

The issue arises when I try to trigger the modal from the child component - it ends up triggering both the child and parent modals (even though no data is passed to the modal triggered by the parent). From my understanding, this happens because I have used the component twice in both parent and child components, as shown below. It's worth mentioning that everything functions as expected from the parent.

I have tried various solutions such as setting a unique key value for each of the components, changing the components' ref name, among other things. I also attempted using v-show to only display the component just before I trigger the parent modal, but this approach is not optimal.

Is there a way to only trigger the modal from the child component?

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>

Answer №1

My previous answer was not satisfactory. I prefer using jQuery to toggle elements in Vue. This method works best for me currently, although there may be better options available.

If you choose to only use Vue, you can pass variables from parent to child components to control the visibility of your modal.

We pass variables using ":", and register events using "@".

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

In the child component, we catch the passed variable using props. We need to specify the type of variable being passed. The main difference between props and data is that values cannot be changed in a child component through props.

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

You can then use this variable to show or hide the modal. Additionally, within the child component, we can create a button to close the modal and emit an event to the parent to update the variable value.

This is achieved by using this.$emit('eventName');

For more information, visit: https://forum.vuejs.org/t/passing-data-back-to-parent/1201

Answer №2

One potential solution is to define the component globally.

For example, in the main.js file:

Vue.component('deleteModal', deleteModal)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Integrating new information into an existing JSON file using React Native

Currently, I am attempting to input new data into an existing JSON file using text input. In my project using React Native, I have a JSON file named PartyInfo.json where certain data is stored. The goal is to have this data passed from a form and saved in ...

Angular factory transforming service

I am looking to transform the 'i18n' function into a factory in order to return a value instead of just setting it. Any suggestions or tips would be greatly appreciated! services.factory('i18nFactory', function() { var language = ...

Navigating cross domain JSONP cookies in IE8 to IE10 can be a real headache

For reasons completely out of my control, here is the current scenario I'm faced with: I have a product listing on catalog.org When you click the "Add to Cart" button on a product, it triggers an AJAX JSONP request to secure.com/product/add/[pro ...

What steps can be taken to solve the JavaScript error provided below?

My objective is to create a new variable called theRightSide that points to the right side div. var theRightSide = document.getElementById("rightSide"); Once all the images are added to the leftSide div, I need to use cloneNode(true) to copy the left ...

Remove the preset text in an input field by clicking on it

Looking for help: <input name="Email" type="text" id="Email" value="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="92f7fff3fbfed2f3f0f1bcf7eaf3ffe2fef7">[email protected]</a>& ...

I'm experiencing difficulty getting my code to function properly when adding or removing classes with Bootstrap Glyphicons

Recently, I decided to play around with bootstrap's glyphicons. By utilizing Jquery's addClass and removeClass functions, I tried to smoothly transition from one glyphicon to another. Here is the code snippet: var glyphOn = true; //The glyphO ...

Updating a $scope variable within a loop in AngularJS

Attempting to modify a $scope variable: Example: $scope.variable_1 $scope.variable_2 ... Desired way of updating it: for (i=0; i<2; i++) { $scope.variable_$i = 1; } Wanting to access "$scope.variable_1" using the "i" index in each loop. Any ...

Turn off escape option when PointerLockControls are in use

Is there a way to prevent the ESCAPE option from being activated (when using PointerLockControls and ThreeJS) by pressing the escape key on the keyboard? I have a different function in mind for this key in my project! Appreciate any assistance in advance ...

Is there a way to conceal the text box in jquery during the initial loading phase?

I have encountered an issue while working on a project. My code only functions properly when I click after it has loaded. I have assigned IDs to each user and implemented code for toggling active/inactive users by passing the ID to each textbox and span el ...

Intelligent javascript jQuery element

It's quite intriguing to see how JQuery library works. By delving deeper into the code, one can understand its inner workings. Take a look at this example below - $.prototype.mymethod=function(str){ alert(str); } //now call the added method $(d ...

Transform an array containing strings into an array containing objects within a JSON property

I have received the following JSON data from an endpoint: { "response": { "lines": [ "[{'line':'3007621h7s2','type':'national'},{'line':'3007663f7s9','type':&apo ...

Loading Animation for Pages and Tables

I'm experiencing a choppy and sudden transition when switching between two pages that contain tables populated using ng-repeat. Upon loading, the footer is positioned halfway up the page below the table heading until the table loads and the layout adj ...

iPhone App Freezes when trying to download a file through Phonegap

Encountering an issue while downloading a file with phonegap: if the internet connection is lost, the application hangs and crashes. The error message received is: * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: ...

Is it possible to change button behavior based on input values when hovering?

Currently, I am attempting to create a webpage where users can input two colors and then when they press the button, a gradient of those two colors will appear on the button itself. <!doctype html> <html> <head> <script src=&apos ...

What could be causing the Angular compile error to occur in this straightforward component?

I have just created this small Angular 4 module: import { BrowserModule } from "@angular/platform-browser"; import { NgModule } from "@angular/core"; import { FormsModule } from "@angular/forms"; import { HttpModule } from "@angular/http"; import { Foote ...

What is the best way to adjust the size of carousel images within a box element?

How can I ensure that carousel pictures are displayed clearly within the box without overflowing? The code I tried resulted in the pictures overflowing from the box and not being visible clearly. How can I resolve this issue? .container { width: 1490px; ...

Vue's animation happens without any delay or duration

I followed the Vue animation instructions from the documentation carefully: The transition component has a name="fade" attribute. v-if is placed in the child of the transition element. The styles were directly copied from the documentation provi ...

Show Pop in relation to modified Text

When the user clicks on the text, a pop-up is displayed after the last word in the text.... https://i.stack.imgur.com/VWQCa.png The logic being used is : left = layer.width + layer.x Code : document.getElementById(lightId).style.left = layer.x + docume ...

Issue encountered with Node's Google Page Speed API implementation

I am facing difficulties in using the Node client for Google PageSpeed API. Every time I run node index.js in the command line, I encounter the following error: /Volumes/folder/pagespeed/index.js:7 }).then(function(res) { ^ TypeError: Cannot read pro ...

Error: ResizeObserver is not defined when using Gatsby with nivo charts

I incorporated @nivo/pie using "gatsby": "^3.13.0", but encountered an error during the gatsby build process. WebpackError: ReferenceError: ResizeObserver is not defined. The version of Nivo being used is "@nivo/pie": "^0 ...