Launching a modal using a method in Vue.js that includes constantly changing content

I am currently developing a feature in my VueJs component that involves opening a modal when a certain condition becomes true, and then retrieving data from a controller to display in the modal.

After searching online, I have not been able to find clear instructions on how to dynamically set content after receiving data through axios.

Below is a snippet of my ModalComponent.vue:

<template>
<div class="modal fade show" id="myModal" style="display: block;">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title"><slot name="modal-header"></slot></h4>
                <button type="button" class="close" @click="$emit('close')" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true" >×</span>
                </button>
            </div>
            <div class="modal-body">
                <slot name="modal-text"></slot>
            </div>
            <div class="modal-footer">
                <slot name="modal-footer"></slot>
                <button type="button" class="btn btn-danger" @click="$emit('close')" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>
</template>

<script>
    export default {
        name: "ModalComponent"
    }
</script>

In another component called ExampleComponent, I demonstrate how to display the modal using a button click event like this:

<button @click="showModal = true">Show Modal</button>
<modal-component v-if="showModal" @close="showModal = false">
    <template slot="modal-header"> Testing something </template>
    <template slot="modal-text"> Text for the Modal body will go here </template>
    <template slot="modal-footer"><button class="btn btn-primary">Save Changes</button></template>
</modal-component>

My goal is to automatically trigger the modal to open if a specific condition is met, retrieve data from the controller, and display it in the modal.

I already have a method in ExampleComponent that fetches data from the controller. However, I am unsure how to insert this data into the modal-text slot and trigger the modal to open.

Any help or guidance would be greatly appreciated. Thank you!

Answer №1

Include

<template slot="modal-text"> {{ modalText }} </template>

in place of

<template slot="modal-header"> Testing something </template>

Next, insert

data () {
    return {
        showModal: false,
        modalText: ''
    }
},
methods: {
    showModalFn: function (showModalData) {
        // your code
        // ...
        this.showModal = true
        this.modalText = 'Whatever you want to display'
    }
}

Answer №2

To demonstrate the process of fetching data, you can utilize the code snippet provided below within the designated method in the mentioned codepen link:

function fetchDataFromServer (url, parameters) {
  if (typeof parameters === "undefined") { parameters = getParametersFromUrl() }
  return axios.get(url, { params: parameters })
  .then(response => {
     return response;
  })
  .catch(function(error) {
     console.error(error)
     return error.response;
  })
}

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

Connect to content on the current page

I am facing an issue where the linked heading of a section on the same page is getting lost under the fixed navigation bar when scrolling down. This problem seems to only occur on desktop view as it works fine on mobile preview. Here is the code I am curre ...

Is it possible to utilize Vue's splice method within a forEach loop in order to delete multiple elements at

I am currently working on an image grid in array form. I am trying to implement a multi-deletion functionality. When a checkbox for each image in the grid is checked, I store the selected image's index in an array called selectedImages. Upon clickin ...

How to Use Google Tag Manager to Track Forms with Various Choices

Currently, I am facing a challenge in setting up conversion tracking using GTM for a form that offers users multiple options via a drop-down menu. When the user clicks on an option, they are presented with choices like A, B, C, and D. After selecting an ...

Sending JSON data from an iOS app to a Flask backend

Within my Flask Python web application, I store certain parameters in SessionStorage to later send back to Flask and save this data as a text file. Interestingly, the process functions perfectly on PCs and Android devices but encounters issues on iOS devi ...

What is the most effective method for applying numerous textures or images to a single Sphere in three.js?

Just like the title says, I'm attempting to create a similar setup to what's showcased on this website: I have the images handy, but I'm currently figuring out how to arrange them all onto a single sphere. Appreciate any guidance you can o ...

Transmit a message from the background.js script to the popup window

Currently, I am looking to integrate FCM (Firebase Cloud Messaging) into my chrome extension. After conducting thorough research, I have discovered that the most efficient way to implement FCM is by utilizing the old API chrome.gcm. So far, this method has ...

Error occurs consistently with AJAX, PHP, and SQL newsfeed

Striving for Progress Currently, I am engrossed in developing a newsfeed and enhancing my proficiency in utilizing Ajax through jQuery. My ultimate aim is to create a seamless user experience where individuals do not need to refresh the page to view the l ...

Sorry, but React does not accept objects as valid children. Make sure the content you are passing is a valid React child element

I encountered an issue with rendering on a screen that involves receiving an object. The error message I received is as follows: Error: Objects are not valid as a React child (found: object with keys {_U, _V, _W, _X}). If you meant to render a collection o ...

The repetition of the react nodejs page load occurs when the get method is utilized

I've successfully set up a page and function for loading the customer list. However, I'm facing an issue where adding the get method to my code results in it being called every time information is received from the URL and the page is rendered. i ...

Bootstrap Popover not displaying information after an AJAX request

I'm struggling to update the popovers contents with Ajax result in my ASP.Net MVC4 project. Using ASP.Net (MVC4): public ActionResult GetEmployeeDetails(string employeeId) { var contract = UnitOfWork.ContractRepository.ContractBu ...

Is it possible to utilize an npm package in TypeScript without a d.ts definition file?

Is it possible to use an npm package in TypeScript and Node.js without a .d.ts definition file? If so, how can I make it work? Currently, my code looks like this and I'm getting an error that says "cannot find module 'node-rest-client'" bec ...

When it comes to utilizing jQuery for the mobile view, how many jQuery libraries are recommended for optimal performance?

I'm currently constructing a website using ROR, and for the mobile view, I've implemented the mobile_fu gem. The designer provided me with a design for the mobile view that includes various jQuery sliders, players, image sliders, drop-down menus ...

Executing mathematical calculations within a JavaScript object

Can an equation be executed inside an object? For instance: var taxes = { gst: '0.10', }; var prices = { first_key: '437.95', total_key: parseFloat(prices.first_key * taxes.gst).toFixed(2), ....... }, }; Or do I n ...

Transform **kerry James O'keeffe-martin** into **Kerry James O'Keeffe-Martin** using TypeScript and Java Script

Is there a way to capitalize names in both TypeScript and JavaScript? For example, changing kerry James O'keeffe-martin to Kerry James O'Keeffe-Martin. ...

The function getElementbyId is not recognized

My JavaScript code is supposed to change the color of a button, but I'm running into an issue where it says that getting the button is not a function. Strangely enough, the same function (with the same capitalization and case) works perfectly just a f ...

Error 404: This page seems to have gone missing. Django and react-router

Struggling to integrate reactjs and react-router (1.x) with my Django project. I'm finding it challenging to make everything work together seamlessly. For more details, you can check out the project on GitHub: https://github.com/liondancer/django-che ...

Unit testing is encountering issues due to errors with objects not being accepted as a React child component

Here is the code where I am testing the functionality of mytestFunc when a checkbox is checked. Checkbox - <input id="mycheck" type="checkbox" onClick={this.mytestFunc} /> mytestFunc function - mytestFunc = e => { const mockdata = this.stat ...

Retrieving a single object in NEXT.JS and MongoDB can be achieved by returning just a single object

Is there a way to retrieve a single object instead of an array from the API? I am specifically looking for just a single "Event" while using MongoDB and Next.js. Currently, I always receive: [{}] But I would like to receive: {} const fetchWithId = (url ...

Buttons and links with intricate geometries

I am currently developing a web application using Java/JSF and I am interested in finding out about technologies that would allow me to define intricate shapes as clickable buttons or links. Right now, my only option is to split an image into smaller trans ...

Choose the right Vue.js component for optimal performance

I have a primary element within which there is a secondary element with vue.js 2.0. The issue arises when the secondary element relies on methods from the primary element. Here's an illustration: Vue.component('primary-element', { tem ...