Update the property prior to calling window.confirm()

Take a look at my code snippet:

<a
  @click="destroy"
  :class="['button', { 'is-loading': deleting }]"
>
  Delete
</a>

data: () => ({
  deleting: false
}),
destroy () {
  this.deleting = true

  if (!confirm('Are you sure?')) {
    this.deleting = false
    return
  }
}

After triggering this code, a modal dialog pops up and this.deleting remains false.

Is there a way to modify the deleting property prior to the dialog appearing?

Answer №1

It appears that the user interface does not update in time for the confirmation dialog to display properly. To resolve this issue, you can introduce a slight delay before showing the confirmation dialog by utilizing setTimeout(func, 0).

You can implement it like this:

destroy () {
  this.deleting = true

  // Keeping reference to `this` for using inside the callback.
  var self = this;

  setTimeout(function() {
      if (!confirm('Sure?') {
        // self - refers to `this` from the outer context.
        self.deleting = false
        return
      }
  }, 0);
}

OR

destroy () {
  this.deleting = true

  setTimeout(() => {
      if (!confirm('Sure?') {
        this.deleting = false
        return
      }
  }, 0);
}

Another option could be using requestAnimationFrame.

For further details, refer to: How to tell when a dynamically created element has rendered

Please note: I have not tested this solution as there is no Minimal, Complete, and Verifiable Example provided in the question.

Answer №2

When the confirm function is triggered and the modal is displayed, the value of this.deleting is set to true. However, if you anticipate that changing this.deleting should result in a different view within the Vue component, this will not occur because the confirm function blocks the process.

To address this issue, it is recommended to encapsulate the native dialog handling for confirm, alert, and prompt in their own function. This approach not only enables asynchronous opening/triggering of the dialogs but also allows for potential replacement with custom dialog boxes in the future.

By utilizing await/async and Promises, the following method can be employed:

Your Dialog Module

const dlgs = {}

dlgs.confirm = function (message) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(confirm(message))
    },0)
  })
}

Your Vue Component

<a
  @click="destroy"
  :class="['button', { 'is-loading': deleting }]"
>
  Delete
</a>


data: () => ({
  deleting: false
}),
async destroy () {
  this.deleting = true

  if (! await dlgs.confirm('Sure?')) {
    this.deleting = false
    return
  }

  // perform the deletion
}

Implementing custom dialog boxes using HTML offers the advantage of being able to update information in the background while the dialog box remains open.

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

What is the process for specifying the type for the createApp(App) function in Vue.js 3?

I'm currently working with Vue3 and Firebase using TypeScript. // main.ts import { createApp } from 'vue' import App from './App.vue' import './registerServiceWorker' import router from './router' import store f ...

Setting Google font icons in a Vuetify expansion panel: A step-by-step guide

I'm facing a challenge when trying to incorporate a Google icon into an expansion panel. Typically, you can specify the icons using the collapse-icon or expand-icon props within either the <v-expansion-panel> component or the <v-expansion-pan ...

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 ...

I'm feeling a little lost trying to navigate my Express app. Can anyone help clarify which specific portion is considered

I'm feeling a little unsure about this, but I'm currently working on an express API app as part of a Codecademy exercise and I'm not quite sure which aspect of the app actually constitutes the API. Essentially, there's a file that cont ...

Caution: Server Components can only pass plain objects to Client Components

My app allows users to search for care homes on a map and add new ones using a form. During development, everything was working fine. However, in production, the map was not updating to show the newly added care homes. It seemed that the API fetching the ...

Issue: Attempting to establish a connection to an SFTP server using ssh2-sftp-client within an AWS lambda function results in a timeout error

My current task involves establishing a connection to an SFTP-Server in order to list the documents located within the /ARCHIVE Folder. The necessary credentials are securely stored in a .env file. Surprisingly, this code runs without issue on my local mac ...

When hovering over, my text and image shift to the left in a strange and abnormal manner

Recently, I made a small code addition to an existing one in order to display text below an image and have the text highlighted in blue on mouse over. Everything seemed to be working fine until I noticed that on mouseover, the text and image shifted to the ...

Jasmine spies call through problem detected

I can't seem to get my code to work properly and I keep encountering this error: TypeError: undefined is not an object (evaluating 'GitUser.GetGitUser('test').then') ... Check out the code snippets below: app.controller(&apo ...

Developing a performant RESTful API using Node.js and MongoDB

As I embark on setting up my first RESTful API with Express and Mongo DB, I am focused on creating a clear pattern that will make the project easy to pick up after a break or for new team members joining. The idea is that whenever an endpoint requires mod ...

AngularJS showcases the full spectrum of available methods

I am struggling to create a method for composing a URL in my class. Here is what I have attempted: The createLink method takes an ID and returns the corresponding URL: console.log("before the method"); console.log($scope.createLink ) $scope.createLink = f ...

Issues occurring with PhoneGap preventing the execution of AngularJS code

I've recently delved into learning AngularJS with PhoneGap and I have a basic HTML code along with some AngularJS snippets. While everything runs smoothly in the browser, only the HTML portion seems to work when I attempt to run it on my Android phone ...

Utilizing SVG technology for precise indoor route navigation

I have been scouring the internet for guides or techniques to create a custom point to point navigation system for an SVG-based indoor floor plan map. Most of the resources I found only work with Google Maps. However, I designed my map using Illustrator as ...

Transmit information from a website to a server located nearby

Creating a home automation hub is my current project -- utilizing a Raspberry Pi as the foundation to display weather updates, control lighting, and more. This setup is connected to a website through a shared MongoDB database, with both systems running Nod ...

Can directive scopes (such as obj.prop) be linked together in a chain?

Here is the directive code I am currently using: template: '<form novalidate class="form-inline" ng-submit="submit($event, building)">' + '<div class="form-group">' + '<label class="form-control-sta ...

JavaScript makes Chrome Hard Reload a breeze

We've created a browser-based app using AngularJS and are currently testing it with a group of clients. One major challenge we're facing is explaining how to "Empty Cache and Hard Reload" using the Chrome browser (by pressing F12, then clicking o ...

The npm package is functioning properly on the vue-cli-service, but is encountering issues on the vite project

I recently developed a basic npm package which includes a single component called MyButton. MyButton is built using Vue 2 (2.7) + composition API to ensure compatibility with both Vue 2 and Vue 3 projects. After thorough testing and production build of my ...

Utilizing ReactJS and TypeScript to retrieve a random value from an array

I have created a project similar to a "ToDo" list, but instead of tasks, it's a list of names. I can input a name and add it to the array, as well as delete each item. Now, I want to implement a button that randomly selects one of the names in the ar ...

The process of integrating Tailwind elements into NextJs version 13

Can anyone help me integrate Tailwind elements into my NextJs project using JavaScript instead of TypeScript? I tried following the documentation, but the navbar component's expand button doesn't work. It seems like all components are having some ...

Displaying all API data by default in Vue.js, even with filters, sorting, and search enabled - how can it be done?

I am currently utilizing Vue.js version 3 and below is the code snippet: <template> <h5>List of Products</h5> <h3>Filter</h3> <button v-on:click="resetOptions">Reset</button> & ...

Trigger animation once you've scrolled past a designated point in the document

I created a count-up counter animation using JavaScript, but the issue is that the counter starts animating as soon as I refresh the page regardless of where I am on the page or if the counter is even visible. I would like the counter to only start workin ...