Guide on developing a Vue modal for transferring user input to a separate component

I have been working on creating a modal component that allows users to input data and then displays it in another component. For example, the user is prompted to enter their first and last name in a modal component (Modal.vue). Once the user saves this information using a submit method on the modal, it is displayed in another component (InputItem.vue).

Currently, my project consists of several components: CreateEvent.vue, Modal.vue, EventItem.vue, EventsList.vue, and app.vue. I have implemented CRUD functionality successfully without the modal component, but when I try to integrate the modal, I start facing difficulties.

I would appreciate any guidance or assistance you can provide to help me navigate through this challenge!

Modal.vue

<template>
  <transition name="modal-fade">
    <div class="modal-backdrop">
      <div
        class="modal"
        role="dialog"
        aria-labelledby="modalTitle"
        aria-describedby="modalDescription"
      >
       <!--- Modal template code goes here --->
      </div>
    </div>
  </transition>
</template>

<script>
export default {
  name: 'modal',
  data() {
    return {
      newTodo: '',
      newEmoji: '',
      idForTodo: this.todos.length + 1
    }
  },
  methods: {
   <!--- Modal methods go here --->
  }
}
</script>

CreateEvent.vue

EventItem.vue

Events.vue

app.vue

Answer №1

To improve the modal component, it is suggested that instead of directly pushing values into the todos array, emit the values. This emitted data can then be listened for by the parent component (App.vue).

An example implementation could look like the following:

Modal.vue

<template>
   ...
// header
<section class="modal-body" id="modalDescription">
  <slot name="body">
    <div @keyup.enter="addTodo">
      ...
    </div>
    <button @click="handleModalSubmit">Create Event</button>
  ...
  //footer
  ...
</template>

<script>
export default {
  ...
  data() {
    ...
  },
  methods: {
    ...,
    handleModalSubmit() {
      this.$emit('todos-have-been-submitted', this.todos);
    },
    addTodo() {
      ...
      this.todos.push({
        id: this.idForTodo,
        title: this.newTodo,
        emoji: this.newEmoji
      })
      ...
    }
  }
}
</script>

App.vue

<template>
  ...
  <Modal
    @todos-have-been-submitted="handleTodoSubmission" //listen for the 'todos-have-been-submitted' event and trigger handleTodoSubmission method upon detection
  />
  <Events 
    :todos="todos" // pass todos as a prop to the Events component
  />
  ...
</template>

<script>
import Events from './components/Events'
import Modal from './components/Modal'

export default {
  name: 'App',
  components: {
    Events,
    Modal
  },
  data() {
    return {
    ...,
      todos: []
    }
  },
  methods: {
    ...,
    handleTodoSubmission(todos) {
      this.todos = [...todos];
    }
  }
}
</script>

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

Refreshing the Table to Update Data

I am working on a jquery application that includes a table with time and number fields. My goal is to increment the values every 3 seconds by creating a function to update the numbers automatically. Initially, the data in the table looks like this: Kobe ...

Ways to ensure a video completely fills the frame

I am experiencing an issue where the video in the main div of my home page does not fully fill the div right away - I have to refresh the page for this to happen. As a result, there is black space on the left and right sides. Interestingly enough, this pr ...

Using a numeral within a Font Awesome icon symbol to customize a label for a Google Maps marker

I have a Google Maps marker displayed below, applying a Font Awesome icon as the label/icon. However, I am unsure how to a.) change the color of the marker and b.) include a number inside the marker. Referencing this Stack Overflow post This is the code ...

Interactive Component overlying Layer - HTML/CSS

Currently, I am working on a web application that features a navigation bar at the bottom of the screen. To enhance visibility, I decided to apply a linear gradient overlay above the underlying elements. This screenshot illustrates what I mean. However, I ...

What causes the "Cannot read properties of undefined" error in Vue when an array is initialized and output is still being displayed?

I am working with two vue files, namely App.vue and a component called UsersPage.vue. UsersPage.vue: <script> export default { data:() =>({ usersList : [] }), methods:{ async createUsersList(){ this.usersLi ...

What is a more efficient method for structuring this React page while making an asynchronous request to the API?

When developing, I encountered this scenario where I needed to ensure that a certain useEffect function only runs once. To achieve this, I established router.query.something as a dependency for the effect. The logic is such that the request will only trigg ...

Can you provide the name of the slideshow plugin used on the Wipro website?

Can anyone tell me the name of the image slide show featured on: http://www.wipro.com/index.htm? Also, does anyone know where I can find the script for free? I am looking to incorporate it into a page that is coded in php, html, css, and javascript. Than ...

- **Rewrite** this text to be unique:- **Bold

Check out this relevant jsFiddle link Below is a list where I aim to make all occurrences of the word 'Bold' bold: <ul id = "list"> <li>Make this word Bold</li> <li>Bold this as well</li> <ul> ...

The ngOnChanges lifecycle hook is triggered only once upon initial rendering

While working with @Input() data coming from the parent component, I am utilizing ngOnChanges to detect any changes. However, it seems that the method only triggers once. Even though the current value is updated, the previous value remains undefined. Below ...

What is the best way to deactivate div elements once an overlay has been applied to them?

My goal is to place an overlay on my form to prevent users from accessing the content. Even though I have added an overlay, users can still interact with input fields. How can I prevent that? .overlay { background: rgba(0, 0, 0, .75); text-align: ce ...

Create a continuous scrolling tool similar to Google Reader for iGoogle

Do you know how to create an infinite scroll widget similar to Google Reader on iGoogle? This widget should be able to dynamically load data as the user scrolls, and replace the traditional scroll bar with a pair of up and down arrows. The HTML structure ...

Even though I included a key prop for each item, I am still encountering the error message stating that every child in a list should have a distinct "key" prop

I have been trying to retrieve data from a rest API and display it as text on my browser. However, I am encountering the following error: index.js:1 Warning: Each child in a list should have a unique "key" prop. Below is how I have set up the key prop. ...

"Error: imports are undefined" in the template for HTML5 boilerplate

After setting up an HTML5 Boilerplate project in WebStorm, I navigate to the localhost:8080/myproject/src URL to run it. Within the src folder, there is a js directory structured like this: libraries models place.model.ts place.model.js addr ...

Utilizing Nuxt3's auto-import feature alongside Eslint

I'm having trouble finding an eslint setup that is compatible with Nuxt3's auto-import feature to prevent no-undef errors. I have tried various packages like @antfu/eslint-config, plugin:nuxt/recommended, @nuxt/eslint-config, @nuxtjs/eslint-confi ...

Refresh the html of the contenteditable element with the most recent targeted information from the textarea

One issue I'm encountering is quite straightforward: selecting/focusing on a few contenteditable elements, then selecting the textarea and changing the HTML of the last focused element from the textarea. However, my problem arises when the textarea tr ...

Having trouble using functions with dynamically loaded content via AJAX in JQuery

I am facing an issue with my code. I am trying to dynamically fetch some data and display it. I have checked the request using firebug and it seems to be successful, but the problem arises when I try to execute the activeImage() function. The images are no ...

Storing notes using HTML5 local storage

I recently developed a unique note-taking web application where users can create multiple notes and switch between them using tabs on the left side. My next step was to implement local storage for saving these notes, so I inserted the following code: $(d ...

Using React-Testing-Library to Jest TestBed Hook in TypeScript for Jest Testing

I'm currently facing a challenge while attempting to integrate the react-hooks library with Formik, specifically using useFormikContext<FormTypeFields>() in TypeScript within my project. I have certain fields where I want to test the automation ...

Manipulate the DOM elements within the ng-repeat directive

Hello, I am currently new to AngularJS and have just begun learning how to create directives. While working on a sample project, I encountered an issue with accessing DOM elements rendered inside my directive. Some elements were not accessible in the link ...

How come my data is not appearing on the screen despite receiving a result in the console log?

I am facing an issue with displaying data obtained from Supabase. I am passing the data as a prop and using map to iterate over it in order to show the required values. However, despite logging the correct results for `programme.title`, nothing is being re ...