The issue of v-bind:checked not functioning properly across all component instances

Presenting a unique radio list component:

<template>
    <div class="list">
      <div class="radio">
        <input type="radio" name="custom-radio-list" :id="'custom-radio-full-' + cid" value="" @change="updateCustomRadio" :checked="selectedOption === ''">
        <label :for="'custom-radio-full-' + cid">All</label>
      </div>
      <div v-for="option in customOptions" :key="option" class="radio">
        <input type="radio" name="custom-radio-list" :id="'custom-radio-' + option + '-' + cid" :value="option" @change="updateCustomRadio" :checked="selectedOption === option">
        <label :for="'custom-radio-' + option + '-' + cid">{{ option }}</label>
      </div>
    </div>
</template>

<script>

export default {
  name: 'CustomRadioList',
  props: ['customOptions', 'cid', 'selectedOption'],
  methods: {
    updateCustomRadio (event) {
      this.$emit('updateCustomRadio', event.target.value)
    }
  }
}
</script>

Implementing this component:

<CustomRadioList :customOptions="customOptions" :selectedOption="selectedOption" cid="1" @updateCustomRadio="updateCustomRadio"/>

In the parent component, simply modify the selectedOption value:

updateCustomRadio ($event) {
  this.selectedOption = $event
},

If using only one instance of this component on the page, it functions correctly. However, when attempting to use it twice in different components, the selectedOption is altered upon clicking either instance, but the check only reflects on the last instance.

An illustrative example has been created here: https://codesandbox.io/s/happy-almeida-8w7jy

Answer №1

To solve the issue, I decided to transform the static attribute name into a dynamic one. Here is how I did it:

<input type="radio" :name="'dynamic-name-' + someVar + '-' + anotherVar" :id="'radio-id-' + someVar + '-' + anotherVar" :value="someValue" @change="updateFunction" :checked="selectedItem === someValue">

Answer №2

The issue occurs because each instance of RadiosHashTags emits an event and all instances catch the same event, leading to only the last instance being affected.

To resolve this issue, you can bind different variables and set unique events to modify them individually.

The code structure remains similar:

<template>
  <div id="app">
  {{ selectTag }} - {{ selectTag2 }}
    <CustomRadio :tags="tags" :selectTag="selectTag" cid="1" @updateTag="updateTag" />
    <hr>
    <CustomRadio :tags="tags" :selectTag="selectTag2" cid="2" @updateTag="updateTag2" />
  </div>
</template>

<script>
import CustomRadio from "./components/CustomRadio";

export default {
  name: "App",
  components: {
    CustomRadio
  },
  data () {
    return {
      tags: ['tag 1', 'tag 2', 'tag 3'],
      selectTag: '',
      selectTag2: ''
    }
  },
  methods: {
    updateTag($event) {
      this.selectTag = $event
    },
    updateTag2($event) {
      this.selectTag2 = $event
    }
  }
};
</script>

If you prefer not to create separate methods for handling events, I recommend exploring Two Way data binding. This feature allows you to define a reactive v-model to modify input variables without requiring additional event handling.

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

Stop Chrome from automatically scrolling to the top of the page when making changes to the DOM

Currently utilizing Action Cable to create a discussion room where users can exchange questions. Upon posting a question, all participants within the room are supposed to see it. Nonetheless, I've encountered an odd issue specifically on Chrome: whene ...

ways of exporting and using arrays in Node.js

Constantly receiving the "undefined" error in main.js: var dbAccess = require('../dao/dbAccess'); dbaInstance = new dbAccess(); var wordPool = dbaInstance.getWordPool(); console.log (wordPool); The contents of "dbAccess.js" are as follows: var ...

Firebase Cloud Function variables causing 'unidentified' output

While experimenting with firebase cloud functions, I'm encountering an issue with a constant error message stating that userID is undefined. It's preventing the function from running smoothly. https://i.sstatic.net/MsnsV.png Below is the databa ...

The response from the Ajax request showed that the data was not

I am working on a page where I need to refresh a specific div every minute without refreshing the whole page. The div retrieves data from a PHP file that calculates the highest price in another XML file. I have learned that the most effective way to achiev ...

The value of useEffect does not change even after it is defined in ReactJS

I am working on a component where I need to fetch data from an API after it has been rendered, and store the response in a useState value. However, when attempting to set the state using the useEffect callback after fetching the API, nothing seems to be w ...

What is the process for including a field specific to a date in a form?

I need the user to select a month and year. In one column, there will be the days of the month they selected [e.g. 1-30]. Users can then add habits in other columns. I want users to be able to input an 'X' for each habit row on a specific date [e ...

Tips for creating a dynamic route with NextJs 14 API

Looking to start a blog with Next.js 14 and I'm working on defining a function in api/posts/[postSlug]/route.js. How do I access the postSlug parameter within this function? Here's my current function code: // api/posts/[postSlug]/route.js impor ...

Concealing video when the source is inaccessible

I am facing an issue with a video element that retrieves its source from a database. The video tag is placed inside a repeater that is bound to the database. My goal is to hide the video if the source is not found in the database. I attempted to use Javasc ...

Utilize React JS to serialize form data for submission via a POST request

I have a simple form where users input text and it triggers an AJAX request to create a new comment. var CommentForm = React.createClass({ propTypes: { // ... // ... }, handleFormSubmit: function(e) { e.preventDefault(); var compo ...

Create a shop without relying on Vuex

I'm currently trying to wrap my head around Vuex, but as I'm still new to the world of VueJS, I'm finding it difficult to grasp. As a result, I'm on the hunt for an alternative solution. My goal is to efficiently share data between tw ...

Transform HTML and CSS into a PDF format using JavaScript

I have a design page in a .cshtml document that displays correctly in all major browsers (FireFox, Chrome, and IE). It utilizes basic CSS for styling and looks great in HTML format. Now, I am attempting to convert one of its DIV elements to PDF. However, ...

Struggling with getting the JavaScript, scss, and CSS television animation to turn on and off properly? Seeking assistance to troubleshoot this

After finding this javascript code on Codepen and seeing that it worked perfectly in the console there, I tried to run it on my computer with jQuery but it didn't work outside of Codepen. Even when attempting to use it on JSfiddle or compile the SCSS ...

Sharing a Promise between Two Service Calls within Angular

Currently, I am making a service call to the backend to save an object and expecting a number to be returned via a promise. Here is how the call looks: saveTcTemplate(item: ITermsConditionsTemplate): ng.IPromise<number> { item.modifiedDa ...

Retrieving all rows from a table using Laravel API and Vue.js

<template> <div class="container"> <div class="row mt-5 mb-3"> <div class="col-md-10"> <h3>Gallery</h3> </div> <div class="col-md-2"> <button class="btn btn-success" ...

Verifying Password Strength with Regex in Jquery

User Name Field should only accept Alphanumeric characters. Maximum of 16 characters allowed, and it must start with a letter not a digit. var usernametest=$("#userName").val() var letters = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,16}$/; if(use ...

Passing an extra variable to the callback function in AJAX and saving the XMLHttpRequest.response as a variable

Attempting to read a local file on the server using the standard loadDoc(url, cfunc) function, my goal is to: 1) Search for a specific string in the file (getLine()); 2) If possible, save that line to a variable. For point 1, I provide a string to the c ...

Difficulty encountered when choosing and interacting with website button with the utilization of Python 3.5.1 and Selenium 2.53.2

I am currently utilizing a Macbook Air that runs on OS X El Capitan. My tool of choice is Python IDLE, and I am attempting to target and interact with the button located on the webpage below: <div class="search-form-actions"> <button class="btn ...

JavaScript objects compared to arrays and JSON format

After countless hours of searching and frustration, I am still struggling to clearly define the distinctions between json, objects, and arrays (in javascript). Take a look at how I've been working with 2-dimensional data containers (trying to avoid us ...

Converting URL for AJAX POST information

While trying to encode a URL using encodeURIComponent, I encountered a 500 SERVER ERROR on certain URLs. It appears that the issue lies in the encoding process, as removing the data resolves the error entirely. What is the correct way to encode the URL to ...

ng-grid cell onclick callback

Currently, I am working with ng-grid and am attempting to define a callback function for when a cell is clicked. During this callback, it is crucial for me to identify the specific row and column of the cell that was clicked. Upon exploring various options ...