Prevent Quasar QDialog from closing when pressing the Escape key under specific conditions

I am utilizing a Quasar dialog to display content, and I want users to be able to close the dialog by pressing the Escape key. However, if a user has made edits within the dialog and hits the Escape key, I'd like to prompt them with another dialog to confirm whether they want to discard the changes to avoid accidental data loss.

The challenge lies in the fact that I have two options - I can either disable the Escape key entirely:

<template>
  <q-dialog
    v-model="showDialog"
    no-backdrop-dismiss
    no-esc-dismiss    
  >
</template>

This approach prevents users from closing the dialog with the Escape key, even if no changes were made. Alternatively, I can allow the Escape key and try to intercept the event:

<template>
  <q-dialog
    v-model="showDialog"
    no-backdrop-dismiss
    @escape-key="dismissDialog"
  >
</template>

<script setup lang="ts">
function dismissDialog() {
  if (unsavedChanges) {
    Dialog.create({
      title: 'Unsaved changes',
      message: 'You have unsaved changes. Do you want to discard them?',
      ok: 'Discard changes',
      cancel: true,
    })
      .onCancel(() => {
        return;
      })
      .onOk(() => {
        emit('dismissDialog');
      });
  } else {
    emit('dismissDialog');
  }
}
</script>

The issue with the second approach is that I can detect unsaved changes easily, but once I exit dismissDialog, the dialog closes automatically without any way to interrupt the closing process.

I have explored using the @before-hide method, but the event returned is always undefined, making it seemingly impossible to intercept the Escape key event and prevent the dialog from closing unless I disable the Escape key entirely.

If anyone has a solution to this dilemma, I would greatly appreciate the insight.

Answer â„–1

If you want to ensure unsaved changes are not lost, you can utilize the @update:model-value event to keep your dialog open.

<q-dialog v-model="firstDialog" @update:model-value="checkUnsavedChanges">
...
</q-dialog>

You can then overlay another dialog on top of the first one by using a different v-model.

function checkUnsavedChanges() {
  if (unsavedChanges.value) {
    firstDialog.value = true;
    secondDialog.value = true;
    return;
  }
  firstDialog.value = false;
}

Within the second dialog, you have the option to choose which dialog to close.

<q-dialog v-model="secondDialog" persistent>
    <q-card>
      <q-card-section>Are you sure?</q-card-section>
      <q-card-actions>
        <q-btn label="Close both" @click="closeAll" />
        <q-btn v-close-popup label="Close only this" />
      </q-card-actions>
    </q-card>
  </q-dialog>
function closeAll() {
  firstDialog.value = false;
  secondDialog.value = false;
  unsavedChanges.value = false;
}

Explore the Playground for more.

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

Maintain the functionality of an object even when it is created using the "bind" method

I'm working with a function that has the following structure: var tempFun = function() { return 'something'; } tempFun.priority = 100; My goal is to store this function in an array and bind another object to it simultaneously, like so ...

The nullish coalescing operator in JavaScript is running code on both of its sides

console.log(restaurant.orderPizza?.('onion','tomato','basil') ?? 'Method does not exist'); console.log(restaurant.orderRissotto?.('onion','tomato','basil') ?? 'Method does not exis ...

Working with AngularJS: Implementing a Service in a Controller

A service has been developed in AngularJS, but it is not being utilized in the controller. Service.js var appService = angular.module("appService", []); appService.service("bddService", function() { var bdds = bdd; this.getBdds = function(){ ...

Steps for sending a request to the root resource

I've encountered a problem that stems from my limited knowledge of Express. Despite creating a project with Express, I'm unable to make calls to the root, only to the routes. I suspect the issue lies in my usage of app.use(...). app.js var inde ...

Angular Functions and Their Application

Just starting out with Angular and facing a challenge with handling downloaded JSON data. I wrote this function: for (var i = 0; i < $scope.Objects.length; i++){ $http.get($scope.Objects[i]["Commit"]).success(function(data) { Commit = data ...

Tips for limiting the frequency of Angular provider loading instances

I have created a provider (I tried with a controller as well, but got the same results). Here is my code: .provider('socketio', function() { this.socket = io.connect("//localhost); console.log("LISTENING..."); this.$get = function() ...

Unable to send information to Vue component

I have two main components: ProfileComponent and UserSettingsComponent. I link the navigation bar to both of these components using <NavbarComponent :user="user"></NavbarComponent>. In the NavbarComponent, I pass the user data retriev ...

Converting R functions into JavaScript using Emscripten

Attempting to convert R functions written in C to JavaScript using Emscripten is proving to be a challenging task. The primary objective at this stage is to migrate a function called pf. The source code for the function can be accessed here. As I navigate ...

JQGrid will automatically conceal any row that contains a false value in a given cell

I'm attempting to conceal a row if a specific cell within it contains the value false. To achieve this, I have experimented with using a formatter in the following manner: $("#list").jqGrid({ //datatype: 'clientSide', ...

Pulling a div from beneath numerous other divs

I have been attempting to create a test case for a web application we are developing and I am on the verge of finding a solution, but there is one final hurdle that has me puzzled... Our requirement is to enable div elements to be draggable (which is work ...

Adjust picture dimensions when the window changes (using jQuery)

Hey there, I'm in need of some help resizing images on my webpage. I want the images to adjust their size when the page loads or when the browser is resized. The images can be either portrait or landscape, and they will be contained within a div that ...

Update the style of the legend from bars to a line chart in chart.js version 2.4.0

https://i.sstatic.net/BXcXj.pngI'm currently using chart.js version 2.4.0 for displaying graphs, and I'm having trouble changing the legend style from bar to line. Is there a way to switch the legend display from bar to line in chart.js? Here i ...

What are the steps to correctly implement async await in a standard sequence?

When I press the button onPress={() => Login()} First, I need to obtain a token by using the signInWithKakao function. Secondly, right after acquiring the token, if it is available, I want to dispatch the profile using the kakaoprofile function. Howev ...

Global variables in AngularJS that are asynchronous

My challenge lies in using AngularJS to create several global objects accessible by any controller within the application. One crucial object I require is a user object containing the user's ID and other essential properties retrieved from the databa ...

"An ExceptionInInitializer error occurred - Can you provide more details,

An Issue Has Arisen: Exception in thread "main" java.lang.ExceptionInInitializerError at com.PoseidonTechnologies.caveworld.level.WoRe.<init>(WoRe.java:46) at com.PoseidonTechnologies.caveworld.CaveWorld.start(CaveWorld.java:80) at com.P ...

Tips for Sending Information to the Current Page Using JQuery

I am attempting to send the form data back to the same location as the form itself. The code needs to: Trigger the click action for #submit Retrieve data from #email, #selection1, and #selection2 Hide the form #form Show the data in #email, #selection1, ...

Restricting the scope of reactivity in a VueJS data store

Goal: I am attempting to create an array of objects retrieved through an API call. After making the initial API call and receiving a single object, I want to store that result and then make another call without updating the original stored object. Challen ...

Unable to retrieve JSON data from the remote URL

I have been attempting to retrieve information from but unfortunately, I am not receiving any data in return. Despite this, I can see the data in my response tab using Google Chrome. My attempts include running it on both a webserver and locally for test ...

What is causing the Jquery form submit event to not trigger?

I am attempting to use jQuery to submit a form. I need the form submit event to be triggered when jQuery submits the form. However, the submit event handler is not being called successfully after the form is submitted. Here is the code snippet: <html ...

Having trouble with vue-router not routing on click?

I'm currently working on implementing a navigation feature that allows users to click and navigate to different Vue components. It's important to note that this application is based on Electron+Vue, but it should function like a regular Vue proj ...