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

Creating a dynamic display of flash files on a webpage through a unique combination of PHP, AJAX, and

Despite my lack of experience with Ajax and minimal java knowledge, I have a strong background in SQL and PHP. Even though I anticipate criticism for this question, I am determined to seek help. My primary objective is to rotate 4 flash SWF files randomly ...

Having trouble getting Vue 3 integration to work properly in Laravel 9 tutorial

Having previously worked on projects using Laravel, I decided to try integrating Vue.js for the front end of my latest project. In search of tutorials on how to seamlessly blend Vue.js with Laravel, I experimented with multiple guides. However, I will focu ...

Loop through a collection of items based on the values in a separate array using jQuery

I have a list of objects below The newlist and SelectID array are both dynamic. I am populating through a function, now I need to iterate and create the new list. var newList = [ { id : 1,name="tea",plant:"darjeeling"}, { id : 2,name="cof ...

The straightforward use of XMLHttpRequest to retrieve the response xhttp.responseText is not functioning properly

I am facing an issue where this.responseText is not returning the content of the file. Can someone assist me in solving this problem? Thank you. Console.log also does not return the content of the file. function loadMegaContent() { var xhttp = new XMLHtt ...

What is the process of redefining the toString method for a function?

I am currently tackling a coding challenge that involves chaining functions. While researching possible solutions online, I noticed that many of them involved using function.toString and overriding the toString method of a function to create a chained add ...

Customize the border style for the span element

I attempted to use the code below in JavaScript/jQuery to adjust the border thickness. Unfortunately, it seems to be ineffective. Can someone please assist me? //$("span").css({"border":"4px solid green"}); document.getElementById("192.168.42.151:8984_ ...

Utilizing JavaScript to enable HTML checkbox to be checked automatically

I am currently working on a constructor that generates checkboxes within a loop. My issue lies in attempting to set these checkboxes as checked, however, it doesn't seem to be functioning correctly. Below is the code snippet: funct ...

Exploring the structure and dispersion of files within a VueJS project: An architectural inquiry

As I delve into learning VueJS, I've come to understand that .vue files typically consist of three distinct parts: <template>, <script>, and <style>. My query pertains to how these three parts are managed in a professional VueJs pro ...

Tips for integrating a Vuetify dialog that can be easily reused

I have been working on creating a reusable v-dialog using Vuetify. I have created the BaseModal component: <v-dialog v-model="inputVal" :hide-overlay="overlay" :max-width="width" > <v- ...

Toggle JavaScript Query Display

Welcome to my HTML test website where I am testing show/hide JavaScript functionality. Upon loading the page, you may notice that everything is hidden until a button is clicked. <html> <head><title>Test</title> <scr ...

Steps to develop a runnable Express API

After developing a basic yet fully functional Node.js Express API application using JavaScript, I am now looking to convert it into an executable file that can be run on Windows systems. The main reason behind this is to provide clients with the option of ...

Using an Ajax Post Call to send FormData leads to a Get request instead

Having trouble with sending a simple form via POST method. I load the form content using AJAX: $(function() { var arg = { "operation": "upload", "step": "0" ...

transferring a document using axios, bypassing the FormData interface

One way to upload a file to the server is by using axios along with the FormData api. Here's an example: persist(photo){ let data = new FormData(); data.append('photo', photo); axios.post(`/api/photos/${this.user ...

Reset the checked state in React JSX to false by using a reset button

After attempting to reset selected radio buttons on this list, it seems like the change I made from {checked} to {user.checked} in input check is causing issues. This modification can be traced back to UserListElement.tsx In an effort to resolve this issu ...

Unable to retrieve an image from various sources

My setup includes an Express server with a designated folder for images. app.use(express.static("files")); When attempting to access an image from the "files" folder at localhost:3000/test, everything functions properly. However, when trying to ...

Encountered an error in Next JS and Graph QL where attempting to destructure the property 'data' from an undefined intermediate value

I am encountering an issue while attempting to make a Apollo request to the SpaceX API. I am receiving a 500 (Internal Server Error) and also at getStaticProps. It's unclear whether this is a syntax problem or an error in my method of implementation. ...

Is Redux really the new trend in the world of action creators?

I am new to this. I'm a bit unsure, is it okay or silly to use the pattern below? import { createAction, handleActions } from "redux-actions"; const CHANGE_STATE = "appState/CHANGE_STATE"; export const changeState = createAction(CHANGE_STATE, (key, ...

Unleashing the Power of Lodash Debounce in Vue

Currently, I have integrated debounce from lodash into my main.js file. import lodash from 'lodash' Vue.prototype._ = lodash I've been utilizing it like this._.find(...), and everything has been functioning smoothly. However, when attemptin ...

Learn how to securely transmit data using basic authentication in Node.js with the node-fetch module

Having trouble with this code. I am facing an issue where a "post" request with basic authentication returns a 200 status, but no response data is received. Surprisingly, when the same code is executed without auth credentials, it works perfectly fine. l ...

Using a CSS button to activate a JavaScript function: A step-by-step guide

My current project involves writing a script to change the color of text when a specific button is clicked. The idea is that clicking the "Change color1" button triggers the text color change using the following code snippet: <button onclick="myFunction ...