Issue with toggling functionality in Vue.js between two identical components

Within the template of another component, I have two components that can be toggled based on clicks on "reply" and "edit" buttons.

<comment-form :model="model" :model-id="modelId" :comment="comment" v-if="showEditForm && canComment" @closeForm="closeForm"></comment-form>
<comment-form :model="model" :model-id="modelId" :parent-id="comment.id" :reply-to="comment" v-if="showReplyForm && canComment" @closeForm="closeForm"></comment-form>

The current issue is that after clicking "edit" and then "reply," it appears that the "edit" form remains open instead of closing and opening the "reply" form as desired.

These methods control the display of the forms:

methods: {
    closeForm: function () {
        this.showReplyForm = false;
        this.showEditForm = false;
    },
    reply: function () {
        this.showReplyForm = true;
        this.showEditForm = false;
    },
    editComment: function () {
        this.showEditForm = true;
        this.showReplyForm = false;
    },
},

I am looking to understand why this behavior is occurring and how to correct it.

For reference, here is the complete comment.vue file:

<template>
     // The rest of the content has been omitted for brevity. 
  </script>

Answer №1

It's quite surprising, but in this case, you require a key. It's unusual to need one outside of a v-for.

The issue arises because you have the same component in two separate v-if conditions. When Vue attempts to update, it recognizes that it should display a comment-form, which is already present. This results in Vue not detecting the changes. While I consider it to be a flaw in Vue, the workaround involves providing a unique key to each instance of the component.

new Vue({
  el: '#app',
  data: {
    showEditForm: true,
    showReplyForm: false
  },
  components: {
    commentForm: {
        methods: {
        close() {
            this.$emit('close-form');
        }
      }
    }
  },
  methods: {
    closeForm: function() {
      this.showReplyForm = false;
      this.showEditForm = false;
    },
    reply: function() {
      this.showReplyForm = true;
      this.showEditForm = false;
    },
    editComment: function() {
      this.showEditForm = true;
      this.showReplyForm = false;
    },
  }
})
<script src="//unpkg.com/vue@latest/dist/vue.js"></script>
<div id="app">
  <button @click="reply">
    Reply
  </button>
  <button @click="editComment">
    Edit
  </button>
  <comment-form v-if="showEditForm" key="edit" @close-form="closeForm" inline-template>
    <div>
      This is the edit form
      <button @click="close">
        Close it
      </button>
    </div>
  </comment-form>
  <comment-form id="reply" key="reply" v-if="showReplyForm" @close-form="closeForm" inline-template>
    <div>
      This is the reply form
      <button @click="close">
        Close it
      </button>
    </div>
  </comment-form>
</div>

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

Warning: Shadcn-UI Form Alert - An element is converting an uncontrolled input to controlled mode

Throughout the course of this project, I found myself repeatedly using const [fileNames, setFileNames] = useState<string[]>([]); and logging the state with console.log(fileNames). However, every time I clicked on the parent element, an empty Array e ...

How to leverage Vue Selectize to fetch JSON data from dropdown options?

I have integrated vue2-selectize to showcase a list of options fetched via an axios call: <template> <selectize v-model="selected" :settings="settings"> <option v-for="option in options" :value="option.id"> ({{ op ...

The app.use function encountered an error stating "Cannot modify header information - headers already sent"

Within my app.js file, I have the following code snippet: app.use(function(req, res, next){ if(!req.user){ res.redirect('/login_'); } next(); }) Upon reviewing the above code, everything appears to be correct. In my route/index.js fi ...

Recognize different HTML components when an event occurs

My application is equipped with a multitude of buttons, inputs, and other elements that trigger different events. I am looking for a way to easily differentiate between each element and the event it triggers. For instance, consider the following snippet f ...

Discover the ultimate guide to creating an interactive website using solely JavaScript, without relying on any server-side

I'm facing a challenge: I have a desire to create a website that is mainly static but also includes some dynamic components, such as a small news blog. Unfortunately, my web server only supports static files and operates as a public dropbox directory. ...

Trouble parsing JSON in Classic ASP

After receiving a JSON Response from a remote server, everything looks good. I discovered an helpful script for parsing the JSON data and extracting the necessary values. When attempting to pass the variable into JSON.parse(), I encountered an error which ...

Nuxt encountering a critical issue: "module 'dir-glob' not found"

Recently, while running my Nuxt app, I encountered an error after restarting the server using npm run dev. The error message stated that it couldn't find the module 'dir-glob'. Despite finding a similar issue on Stack Overflow related to Ang ...

What is the preferable method: passing in $event or implying it?

Which approach is preferable: passing in the event when using it in a method or relying on implicit handling? Method 1: <input @keyup.enter="chooseMe($event)"/> Method 2: <input @keyup.enter="chooseMe"/> chooseMe(evt) { ...

Utilizing titanium to develop a functionality that listens for button presses on any area of the screen

I am trying to simplify the action listener for 9 buttons on a screen. Currently, I have individual event handlers set up for each button, which seems inefficient. Is there a way to create an array of buttons and manipulate them collectively? For example ...

I am having difficulty retrieving information from the Laravel API

I am struggling to retrieve data from my Laravel application and display it in Vue CLI. While I can see the response, I am encountering difficulties when trying to show it in the Vue application. https://i.stack.imgur.com/tCgrd.png Whenever I attempt to f ...

Using Angular to Bind JSON Data

I'm currently in the process of evaluating different JS frameworks for a project and I find myself torn between Angular and Ember. As I continue to explore Angular, I have a specific question regarding data binding to an external json file stored on S ...

Guide on integrating a JavaScript control (JavaScript package) obtained from GitHub into my asp.net application

Hello everyone, I am a newcomer to GitHub and have some basic questions to ask. Recently, I downloaded the package from https://github.com/jspreadsheet/ce in .zip format for using in my asp.net web application. However, I am not sure how to incorporate the ...

Determine the number of items (within an array) that were created within the past few days, weeks, and months leading up to the 'current time'

Having an array filled with objects containing timestamps: Here is a glimpse of the data: const dataList = [ { _id: "602102db3acc4515d4b2f687", createdDt: "2021-02-08T09:22:35.000Z", }, { _id: "6021024da706a260d89 ...

Turning off devtools in Next.js

Currently, my focus is on developing an application using Next.js and I am in search of a way to prevent the opening of devtools. While exploring npm packages, I came across a promising tool called Disable-devtool - npm link. However, Next.js keeps present ...

Create an unordered list using the <ul> tag

Creating a ul as input is my goal, similar to this example on jsfiddle: http://jsfiddle.net/hailwood/u8zj5/ (However, I want to avoid using the tagit plugin and implement it myself) I envision allowing users to enter text in the input field and upon hitt ...

Verify whether an email is already registered in firestore authentication during the signup process using Angular

When a user signs up for our app, I want them to receive immediate feedback on whether the email they are attempting to sign up with already exists. Currently, the user has to submit the form before being notified if the email is taken or not. This desire ...

Issues with Ajax arise once URL re-routing is activated

When loading content using AJAX and ASP.NET web-methods, the following code is used to trigger the Ajax request: var pageIndex = 1; var pageCount; $(window).scroll(function () { if ($(window).scrollTop() == $(document).height() - $(window).height()) ...

Enhance the HTML content using a JavaScript function

Here is the code that I have: <label>Brand</label></br> <select name="brand" id="brand" onChange="changecat(this.value);"> <option value="" selected>Select Brand</option> <option value="A">AMD</option&g ...

Erase Photo from Server by Simply Clicking on the Remove Button NodeJS (And Removing the Image Title from the Database)

I have a button that successfully deletes an image name from a mySQL table. However, I also want it to delete the actual image from the server. Below is the code snippet from my index.js: document.querySelector('table tbody').addEventListener(&a ...

Unable to display image in jqGrid binary format

In our system, we use a standard function to retrieve images stored as binaries in the database, and this function works seamlessly throughout the entire system. However, when implementing jqGrid, I encountered difficulties using the existing structure as ...