"What is the best way to have a data toggle in Vue that waits for the success or failure of

How can I ensure that the modal is triggered only after a successful axios response, without altering any existing styles? The current code triggers the modal before waiting for the axios response, despite adding v-if.

Current code:

<template>
<div>
    <div class="col-12 text-center">
        <a @click="func()" class="btn btn-sm btn-round btn-success save-button" data-toggle="modal" data-target="#success-save">submit</a>
    </div>


    <div v-if="modalDisplay" class="modal modal-top fade" id="success-save" tabindex="-1" role="dialog">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-body">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
                <h3 class="text-center" style="color:white;"><strong>Success</strong></h3>
                </div>
            </div>
        </div>
    </div>
</div>
</template>

<script>
export default {
    data() {
        return {
            modalDisplay: false,
        }
    },
    methods: {
        func() {
            axios.post('/some/uri', {
                'content': 'abc',
            })
                .then(response => {
                    this.modalDisplay = true;
                });
        },
    }
</script>

I have attempted to adjust the positioning of v-if and other elements, but the issue persists. Your guidance on resolving this matter while maintaining the current style will be greatly appreciated. Thank you!

Edit: I'm using Vue 2.6.11 Modified the code

Answer №1

When working with Vue 2.x, it is important to remember that templates should have only one element inside them. To resolve this, try enclosing all the tags within a div as shown below:

<template>
  <div>
    <div class="col-12 text-center">
        <a @click="func()" class="btn btn-sm btn-round btn-success save-button" data-toggle="modal" data-target="#success-save">submit</a>
    </div>
    <div v-if="modalDisplay" class="modal modal-top fade" id="success-save" tabindex="-1" role="dialog">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-body">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
                <h3 class="text-center" style="color:white;"><strong>Success</strong></h3>
                </div>
            </div>
        </div>
    </div>
  </div>
</template>

Additionally, make sure to add a cache block to your axios call:

axios.post('/some/uri', {
            'content': 'abc',
        })
            .then(response => {
                this.modalDisplay = true;
            })
            .catch(error=> {
                console.log(error);
            });

If you are working with Vue 3, you have the option to use fragments to avoid wrapping elements into a single node.

You can view the implementation here

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

Textfield with predictive text suggestions

I am currently working on implementing an autocomplete textfield for my Rails application, following the example from the Agile Web Development with Rails, 3rd Edition. However, when I try to insert their demo code: <%= stylesheet_link_tag &apo ...

Create a simulated reload of the window location using sinon

Currently, I am working on creating tests using sinon for a specific section of Vue code that triggers a page reload with window.location.reload();. Even though the code functions properly, the test is encountering a failure with the error message Error: ...

A guide on Extracting Values from Nested Objects

Although I am not well-versed in JavaScript, I have a small project where I need to use JavaScript. I am attempting to retrieve values from an object nested within another object. However, my code is throwing errors. Below is the snippet of my code with d ...

Ways to retrieve a returned value from mongoose

I am attempting to retrieve a value from a mongoose callback function, but I keep encountering an error stating TypeError: #<Object> is not a function. I understand that it may be tricky to achieve this, but the way I am querying the database require ...

A guide on displaying data in a table using a select dropdown in a pug file and passing it to another pug file

After creating a single page featuring a select dropdown containing various book titles from a JSON file, I encountered an issue. Upon selecting a book and clicking submit (similar to this image), the intention was for it to redirect to another page named ...

Angular 2 Encounter Error When Trying to Access Undefined Property in a Function

Element: import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-ore-table', templateUrl: './ore-table.component.html', styleUrls: [&a ...

Passing predefined functions to asynchronous functions can be achieved by simply defining the

I am facing a challenge in passing a predefined function within an async function. The piece of code below is functioning flawlessly: async.auto({ getAccessToken: function (callback) { let x = { access_token: signToken({ userId: u ...

Interacting with JSON API data in real-time using AJAX and the power of JQuery

I'm currently working on displaying data dynamically from an API, and everything is functioning well except for the "Next" and "Previous" links. I can't seem to get them to update the value count in the search bar. My problem lies in executing my ...

Chrome geolocation feature does not display the permission popup for JavaScript

After the latest Chrome update, we have noticed that the popup to Allow/Block accessing a user's location from a website is no longer appearing. We tested this on Edge, Firefox, and different mobile devices, where it seems to be working fine. Current ...

Creating dynamic computed properties at runtime when interacting with the Vue instance

Is there a way to programmatically create computed props while still being able to access the instance for dynamic values? For example: <script> export default { computed: { ...createDynamicPropsWithTheContext(this), // helper function that re ...

Encountering difficulties while attempting to delete with a router.delete command - receiving a 404 not

Within my application, I am passing the request parameter 'id' in the router.delete method and communicating it with the Vuex service. However, when triggering the action, an API call is made but it results in a 404 error indicating "not found" a ...

Browser encountering HTTP response that has been shorted extensively

When making an HTTP post request using axios, I am encountering an issue where the body of the response is a large 4MB string. axios({ method: 'POST', url: url, data: data, headers : headers, }) .then(function (response) { co ...

Tips for modifying an HTML element's attribute when a button is clicked, both in the client and server side

Context: This question delves into the fundamental concepts of AJAX. I have been studying this tutorial along with this example for the JavaScript part, and this resource (the last one on the page) for the PHP segment. Imagine a scenario where a JavaScri ...

Tips on extracting information from an AJAX call using JQuery

My current project involves utilizing a webapi in asp.net that outputs JSON data. I am looking to integrate this webapi with JQuery within a php-created website. The following is the JQuery code I am using to retrieve information from the webapi: $.ajax( ...

Checking for the existence of a file in JavaScript

I rely heavily on the scripts and images on my website, but the problem is that everything gets saved to the cache. This means that users can't see updates unless they clear their cache or open the site in private browsing mode. I'm working on cr ...

Strategies for Effectively Managing Null Checks in Your JavaScript Project

When retrieving data from the BE API, it is in the format: { "details": { "address": { "street": "123/4", "city": "Banglore" } } } In our React project, we access this dat ...

An error occured: Unable to access undefined properties (specifically 'hasOwnProperty')

I encountered an issue and managed to solve it. I am currently working on creating an update profile page for my Express app using Mongoose, but I keep getting the error "TypeError: Cannot read properties of undefined (reading 'hasOwnProperty')". ...

Discover and eliminate the style attribute through a click action

I've been struggling to find a solution to remove the style attribute from a specific tr tag within a table when it is clicked. I've tried several lines of code but none seem to work. Here's the link to the fiddle for reference: http://jsfi ...

Using a text box in jQuery to perform basic calculations is a straightforward process

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Creating a Lens Calculator Web App</title> <link href="http://code.jquery.com/mobile/1.0a3/jque ...

Tips on preventing the need for null or undefined checks in JS/Typescript singletons that have an initialization function

Is there a way to streamline the process of handling props in an Object literal that is dynamically initialized only once? I'm looking for a pattern that would eliminate the need for repetitive null/undefined checks and throw errors when certain metho ...