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

Pass multiple variables as input to a function, then query a JSON array to retrieve multiple array values as the output

My JavaScript function contains a JSON array, where it takes an input and searches for the corresponding key/value pair to return the desired value. I am attempting to input a string of variables like this: 1,2,3,4,5 Into this function: function getF(f ...

How to create a manual mock for @material-ui withStyles in React using Jest

I have been experimenting with creating manual mocks for the @material-ui/core/styles module, specifically targeting the HOC known as withStyles. Initially, using an inline mock with jest.mock function worked flawlessly. However, when attempting to reloca ...

Utilize the WebGLRenderTarget again

In my project, I am working with two scenes: the main scene which displays a textured plane, and a secondary scene that needs to be rendered to a texture. This texture will serve as a map for the main scene's plane. Although most THREE.WebGLRenderTar ...

Creating a dropdown menu in Vue.js with a nested array

Upon receiving a response from the Zoho API, I am faced with an array structured as follows: { "response": { "result": [{ "4076840000001": [ { "Department": "Department 1", " ...

Regex: Enabling commas in the name of an Excel file

My JavaScript code is set up to extract data from an excel file. As a first step, I define a regular expression and assign it to a variable named regex var regex = /^([a-zA-Z0-9\s_!()\\.\-:])+(.xls|.xlsx)$/; Following this, there is s ...

Insert a picture within the text input field

I'm facing a specific scenario where I need to add text followed by an image, then more text followed by another image and so on. Please see the input text with values in the image below. Can someone guide me on how to accomplish this with jQuery and ...

Having difficulty parsing or assigning JSON response: The response is being interpreted as [object Object]

Working with the Flickr API, Javascript/JQuery, and AJAX, I have the following code: function getRequest(arguments) { var requestinfo; $.ajax({ type: 'GET', url: flickrurl + '&'+ ...

The router is unable to direct when an item is clicked

I am encountering an issue with my routing setup - when I click on an item in the list-item component, it does not successfully route to the detail-component. Here is a glimpse of my source code: product-list.component.html: <h1>Product List Compon ...

Generating a fresh array by filtering out elements with specific properties using the .map() method

Within my React application, there exists an array containing key value pairs where each pair corresponds to a checkbox. Upon checking the checkbox, the value of the corresponding key switches between true and false. The structure of the data retrieved is ...

Vue.js - When Property is Undefined and How to Render it in Browser

My experience with Vue has been quite puzzling. I've encountered an issue while trying to render a nested property of an object called descrizione, and although it does work, I keep receiving a warning from Vue in the console: TypeError: Cannot rea ...

Verifying if a dropdown option has been chosen through validation in JavaScript

Currently, I am working on implementing a validation block in my JavaScript code to ensure that users have selected a value before proceeding. If a value is not selected, I want to display a pop-up message prompting them to do so. function validate(form) ...

Error message in vuejs: JSON parsing error detected due to an unexpected "<" symbol at the beginning

I have been trying to troubleshoot this issue, but I am having trouble understanding how to resolve it. Currently, I am using lottie-web in a project and need to set the animation parameters on an object in order to pass them as a parameter later. This i ...

How can we eliminate duplicate arrays of objects within a multi-dimensional array using ReactJS and JavaScript?

let galleryItems = [ {id: 1029, name: 'College-Annual-Day.jpg', ext: 'jpg', mime: 'image/jpeg', size: 91153, …}, {id: 1029, name: 'College-Annual-Day.jpg', ext: 'jpg', mime: 'image/jpeg', si ...

Saving numerical data from Firebase using Vue.js

I am currently using Firebase in combination with Vue.js. When saving data to the database, I execute the following command: saveEvent(){ db.collection('events').add({ title: this.title, content: this.content, start: this.start, ...

What could be causing the issue with the Vue CLI not working after installation via npm 6.9.0?

Whenever I try to run the command below: vue create hello-world I receive this message : 'vue' is not recognized as an internal or external command, operable program or batch file. It's been a month and I'm still struggling to fin ...

Unlocking protection: Confirming password strength and security with password indicator and regular expressions for special characters in angular through directive

I have developed an app for password validation using an AngularJS directive. The requirements for the password include at least one special character, one capital letter, one number, and a minimum length of 8 characters. Additionally, I have included a pa ...

Is there a built-in constant in the Angular framework that automatically resolves a promise as soon as it

I'm facing a situation where I have code that checks a conditional statement to decide if an asynchronous call should be made. If the condition is not met, the call is skipped. However, I still need to perform some final action regardless of whether t ...

Establishing the properties of an object as it is being structured within a nested data format

I am in the process of creating a unique JSON representation, focusing on object composition to directly set key values during composition. However, I've encountered difficulty composing multiple objects in a nested manner. My goal is to find an expr ...

Exploring MongoDB's $in and $ne Operators

Looking to retrieve some Documents based on a field that may exist in an array if a filter is applied. However, I also need to ensure that the same field does not equal null unconditionally. While using $in: [some values] can prevent null from being includ ...

Exploring Vue.js with the composition API, delving into the world of "Mixins" and mastering life-cycle hooks

I've been searching everywhere (and coming up empty-handed) for a solution to the following question. In Vue 2.x, I was able to utilize mixins for life-cycle hooks. For example, I could create a file Mixins.js with: export default { created() { ...