"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

Error: Unable to assign values to undefined properties (specifically 'styles') when using withLess, withSass, or withCSS in next.config.js within Next.js

I have been attempting to set up a NextJS 12 project with custom Ant Design. Following some examples I found, it seems I need to configure my next.config.js file with the libraries @zeit/next-sass, @zeit/next-less, and @zeit/next-css. However, when I try t ...

Exploring the process of iterating through a JSON post response and displaying its contents within image divs

After receiving a JSON post response, I am looking to iterate over the data and display it in image divs. Can anyone provide guidance on how to achieve this using JavaScript? Thank you. Here is the JavaScript code that handles the JSON post response: cor ...

How can you use JQuery to assign a single function as an onClick handler for multiple radio buttons?

I have a custom function named handleOnClickRadio(i, j);, and multiple radio buttons with the IDs in the format of id="something-radio[i][j]". These radio buttons are all contained within a table labeled "bigtable". Is there a way to link the function han ...

Is it possible to update the CSS file of an external SVG file in real-time?

Is there a way for an SVG image to reference another CSS file? A webpage contains an SVG file. A button allows users to switch between classic colors and high contrast mode on the entire webpage, including the SVG image. Attempt w.css (white backgrou ...

What is the reason behind Meteor automatically updating a record without the need to run a "Meteor.call" function for an update?

I am currently developing a Meteor.js application and while I have grasped the basic concepts of Meteor, I feel like I might be missing something when it comes to its reactivity principles. Using angular-meteor, I am utilizing a $scope variable in my view ...

Utilizing AngularJS: Establishing a Universal Parent State in UI-Router for Modals and Shared Components

In my code using UI-Router and Bootstrap-ui modal, I have defined the state as shown below. reference var state = { name: 'modala', parent: 'home', onEnter: function($modal, $state) { modalInstance = $modal.open({ ...

Having trouble retrieving JSON data from an external URL in AngularJS when making a $http.get call and using the success method?

Code in the Controller.js file: let myApp=angular.module('myApp',[]); myApp.controller('myController', function($scope,$http){ $http.get('data.json').success(function(data){ $scope.art=data; }); }); ...

Understanding Node.JS: A Dive into Key Concepts

Forgive my lack of knowledge, but I'm really trying to grasp the differences between Node.js and Backbone.js. I believe I'm getting there, but could someone confirm this or guide me in the right direction? Node.js is a platform that can handle H ...

Display time series data from PHP by utilizing Flot Charts in jQuery

After receiving data from a database, which is formatted using PHP and returned as a JSON response for an Ajax call, I encountered an issue. Everything works fine and the data is plotted except when the X-Axis contains dates, in which case nothing gets plo ...

What is the best way to ensure that a specific number of XHR callbacks have successfully completed before proceeding with further actions?

I have four requests that each have their own callback and can fire in any order. However, I need all the callbacks to finish successfully before executing mergeData. The issue with my current approach is that the initial parameter values do not refresh ...

Locate the final child element within a specified div using JQuery

I am looking to create a web application that allows users to input a question and select from multiple answers. I need to be able to dynamically add extra answer fields when the plus button is clicked, but only within the specific formRow (refer to the co ...

Learn how to toggle the visibility of three div elements arranged horizontally

$(document).ready(function () { $("#toggle").click(function () { if ($(this).data('name') == 'show') { $("#sidebar").animate({ width: '10%' }).hide() $("#map").an ...

The UglifyJsPlugin in Webpack encounters an issue when processing Node modules that contain the "let" keyword

Below is the code snippet from my project which utilizes Vue.js' Webpack official template: .babelrc: "presets": [ "babel-preset-es2015", "babel-preset-stage-2", ] webpack.prod.config.js new webpack.optimize.UglifyJsPlugin({ compress: { ...

Managing errors with async/await in an Angular HttpClient function

I have been experimenting with an async/await pattern to manage a complex scenario that could potentially result in "callback hell" if approached differently. Below is a simplified version of the code. The actual implementation involves approximately 5 co ...

Discovering the Essence of AngularJS Test Runner: Unraveling the

I recently started learning Angular JS and decided to follow the tutorial here. I've encountered a roadblock in step 8 where I need to write a test to check if the thumbnail images are being displayed. The concept behind it is simple. There is a JSON ...

PHP and MySQL form is not being updated with new data

In my database, the fields include: id,name,email_id,address,phone_no,username,password,category,date <?php include_once('connect_to_mysql.php'); if(isset($_POST["submit"])){ $a=mysql_real_escape_string($_POST["name"]); ...

The interaction issue in Ionic 4 with Vue js arises when the ion-content within the ion-menu does not respond to clicks

My Vue app has been set up with Ionic 4 using @ionic/vue. Below is the code snippet from the main.js file: import Vue from 'vue' import App from './App.vue' import router from './router' import store from './store&apos ...

Unable to refresh the view from the controller once the promise has been resolved

On my webpage, I want to display a dynamic list of items that updates whenever the page is refreshed. To achieve this, I am using Parse to store and retrieve my items using promises. Here's a simplified example of how it works: When the index.html pa ...

Is there a way to detect and intercept M-SEARCH requests in Express?

Here is my Express program designed to capture M-SEARCH requests: router['m-search']('/', function(req, res, next) { res.send('Received an M-SEARCH request\n'); }); This code specifically responds to the following r ...

Looking to use regex to search through a webpage's text content written in JavaScript

I am struggling with the re.search function and how to use it effectively. I have a block of text/javascript that I need to extract in order to convert it to json using json loads. $(function() { $product = $('#product-' + 12272257171); ...