Pay attention to the Ref<string> changes in Vue, even if the value is updated to 0, the previous value should still be considered

I encountered an issue with Vue3's watch or onUpdated:

Although I can successfully trigger the callback using both, there is a particular scenario that poses a problem:

  1. A user clicks on the Delete button and sets the targetId to someId
  2. The <Modal/>'s watch is triggered as the props.id changes, displaying a bootstrap Modal
  3. If the user accidentally clicks outside the modal and hides it
  4. When the user tries clicking the Delete button again, even though the targetId is still set to someId, the <Modal/>'s watch does not trigger. As a result, the modal does not reappear

As seen in my code snippet, I attempted to reset targetId to 0 every time showModal was called, but this did not resolve the issue. It seems that although targetId did change twice, it is not being "watched" by the <Modal/>

Essentially, my goal is to trigger the watch or onUpdated even when the old value equals the new value (I understand this may not be directly possible). Thus, I tried setting it to a default value and then changing it back, hoping to provoke two changes ("oldVal -> 0" and "0 -> oldVal"), but this approach also did not work.


<!-- Parent -->
<template>
  <button @onclick="showDeleteModal(someId)">Delete</buton>
  <Modal :id="targetId"/>
</template>

<script setup>
   const targetId = ref(0)
   const showDeleteModal = (id)=>{
      <!-- Changing to 0 then back to id does not work -->
      targetId.value = 0
      targetId.value = id
   }
</script>



<!-- Child(Modal) -->
<template>
   some template
</template>

<script setup>
   const props = defineProps({id: Number})
   watch(()=>props.id, ()=>{
      <!-- Show the Modal here -->
   })
</script>

Answer №1

Trying to toggle the value within the same function doesn't yield desired results as change detection only occurs after the function finishes execution. A more suitable approach would be utilizing nextTick():

import { nextTick } from 'vue'
const toggleValue = (newValue) => {
  currentValue.value = 0
  nextTick(() => currentValue.value = newValue)
}

Nevertheless, this method may cause the action to be triggered twice and can seem clumsy. It might be worth exploring an alternative where the value is reset when the modal closes.

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

The attribute 'subtle' is not found within the definition of 'webcrypto' type

Currently, I am working with Node v17.4 and I am looking to utilize the webcrypto API. Referencing this specific example, I am attempting to include subtle in my project, but TypeScript is throwing an error: Property 'subtle' does not exist on ...

Is it possible to authenticate both users and admins within the same collection in Mongoose when using Node.js with Express? Can aggregation be used for this purpose?

this is my custom schema const mongoose = require ('mongoose'); const adminSchema = new mongoose.Schema({ name:String, password:String, user:[{ name:String, email:String, password:String } ] }) var ...

Unshifting values in a JavaScript array only if they exist in another array

I have two arrays of objects - one containing selected data and the other containing general data that needs to be displayed General data for display const arr = [ { id: "1", name: "Skoda - Auto" }, { id: "2" ...

Displaying videos in Vue js with full width and height is not working as expected

I am trying to create something similar to this: https://i.sstatic.net/R8VEy.png However, the video does not display in full height and width. Instead, it appears cut off at the edges and I cannot see the controls. I want the video to cover 100% of the ...

Show a loading icon as the synchronous Ajax request is being sent

Seeking a way to show a spinner while making a synchronous Ajax request to fetch data from the server. Acknowledging that asynchronous mode is preferred, but not permitted in this case. Aware that a sync ajax request can cause browser blocking. An attemp ...

Guide on calling an async function within a readable stream in node.js

Here is a brief example showcasing the implementation of a custom readable stream named MyStream. This stream retrieves file/folder names from a directory and sends the values to the data-event. In this demonstration, I have implemented two different meth ...

Storing form data in a file using React

I am trying to create a feature in my react component where instead of submitting a form and sending the data, I want to write this data to a file for later use. Is it achievable using vanilla JS or should I consider using a library? This is how my handl ...

How can I prevent div duplication when working with ui-router?

I created a basic demonstration to get familiar with ui router. Unfortunately, I encountered an issue of duplicated views when utilizing ui router. Below is the snippet of the stateProvider section: app.config(function($stateProvider,$urlRouterProvider) ...

Tracking Time Spent in a Tab using HTML and JavaScript

I have a unique issue that requires a specific solution. Despite my extensive search across the internet, no useful answers were found. This is the snippet of HTML code in question: <form action="/timer.php" method="POST"> <span>Fir ...

Efficiently handling multiple form submissions using a single jQuery Ajax request

I'm working on a page that has 3-4 forms within divs, and I want to submit them all with just one script. Additionally, I want to refresh the content of the specific div where the form is located. However, I'm unsure of how to specify the current ...

Creating a dynamic name in TypeScript for an object to be utilized in an onClick event

If I have a TypeScript object declared in my view like this: <script type="text/javascript"> var myTSObject = Module.CustomClass('#someId'); myISObject.bind(); </script> Now, if I need to manage a click event from within the ...

Creating a way for a URL to be easily navigated using VueJS

Forgive me for not knowing the right terms for my current dilemma, which is probably part of the issue... I've developed a Single Page Application (SPA) using VueJS to create a small portfolio site. I have set up a /information route using VueRouter. ...

Exploring the capabilities of JQuery's attributes

If I have the following div elements: <div class="hat" rel="cap"> <div class="hat" rel="pine"> <div class="hat" rel="mouse"> What is the JQuery syntax for executing a "where" condition? Here's an example: $("div.hat").remove WHER ...

Empty Angular-chart.js Container

How can I resolve the issue of getting a blank div and no output while trying to display a chart where the options, labels, and other data are initialized in the TypeScript controller and then used on the HTML page? I added the angular-chart.js library us ...

Are there any nodeJS template engines similar to C#'s RazorEngine?

Is there a template engine for Node.js that is similar to RazorEngine, specialized in generating HTML but also capable of handling other types of output? I am looking for a tool that can dynamically create JavaScript files along with HTML content like Razo ...

Guide to ordering two arrays using a common randomized sorting method

Currently, I am working on a quiz application using jQuery and JavaScript. In the code snippet below, I have a function that is supposed to randomize a set of possible answers for a question along with corresponding photos. Each photo matches one of the a ...

Enter key always causes the Bootstrap form to submit

I am working with a jquery function: $("#get-input").keyup(function (event) { if (event.keyCode === 13) { $("#get-data").click(); } }); $("#get-data").click(function (e) { var endpoint = $(".get-input").val(); if ($('#data-d ...

Numerous Voxels showcasing an array of unique textures. Optimal performance guaranteed

Is it possible to add multiple voxels (cubes with different textures) to the same scene in a more efficient manner? When I try to add more than 500 voxels, I encounter serious performance issues. Below is the code I am currently using: texture = createT ...

Using webpack with the production parameter

Currently working on an Express+React application which utilizes webpack for bundling. During development, I have been using "webpack --watch", but as I prepare to deploy to production, I am interested in uglifying my JavaScript code. Unfortunately, the ...

Tips on integrating googleapis with apps script

My goal: I am trying to implement the Google Calendar's API acl.list() in a Google Script using the UrlFetchApp.fetch() function. Issue: The Google script itself has an OAuth token when it runs. However, the problem arises when the UrlFetchApp.fetc ...