Removing Component Items in a Vue.js v-for Loop

I recently created a Vue radio button component and I'm having trouble figuring out how to delete the selected values. While my current solution deletes the actual values, the selection still remains visible.

Below is the code for the component:

<template id="fradio">
<div>

<div class="field is-horizontal">
  <div class="field-label" v-bind:class = "{ 'required' : required }">
    <label
        class = "label"
        >{{label}}
    </label>
  </div>
  <div class="field-body">

  <div>
    <div class="field is-narrow">
      <p class="control" v-for="val in values">
        <label class = "radio">
          <input 
            type="radio"            
            v-bind:name = "name"
            v-bind:id = "name"
            @click = "updateValue(val)"
          >
          <span>{{val[valueLabel]}}</span>
          <span v-if="!valueLabel">{{val}}</span>
        </label>
        <label class="radio">
          <button class="delete is-small" @click="removeValue"></button>
        </label>  

        <slot></slot>
      </p>      
    </div>
   </div>


</div>
</template>

<script>
    export default {
        props: {

            label: {
              type: String,
              required: true,
            },

            inputclass: {
                type: String,
            },
            required: {
                type: Boolean,
                default: false,
            },
            valueLabel:{
                type: String,
            },
            returnValue:{
                type: String,

            },
            values:{},
            name:'',
        },
        data() {
            return {

            };
        },


methods: {

    updateValue: function (value) {
        var selectedValue;
        (!this.returnValue) ? selectedValue = value : selectedValue = value[this.returnValue];

      this.$emit('input', selectedValue)    
    },

  removeValue: function() {
    this.$emit('input',null);
  },

},

}

</script>

Although it seems simple, I would appreciate some help in identifying the issue...

Answer №1

Update:

Upon further reflection, it appears that the issue may lie in the parent component where the data is not dynamically updating. This could be causing the problem of the data not being updated as intended. Since most of the data is passed down as props, I would need to review how the event is triggered in the parent component to identify the issue. From the code snippet provided, it seems like the removeValue() function emits an event but there is no code actually removing the value.

I suggest checking the parent component to ensure that it properly removes the child component, which should resolve the issue at hand!

Initial Answer:

In general, when removing an item from a list generated by a v-for loop, you need to know the index of the item and then use the Array.splice() method to remove it from the list.

Here's a simple example to illustrate this concept:

<template>
    <ul>
        <li v-for="(fruit, index) in fruits"      
            @click="removeItem(index)">
            {{ fruit }}
        </li>
    </ul>
</template>

<script>
    export default {
        data() {
            return {
                fruits: ['Apple', 'Banana', 'Clementines']
            }
        },
        methods: {
            removeItem(index) {
                this.fruits.splice(index, 1)
            }
        }
    }
</script>

Feel free to reach out if you have any questions or need further clarification!

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

Attempting to resolve the Bootstrap issue, currently in search of a suitable solution

Today I made the decision to utilize bootstrap to create a menu, but unfortunately, I've encountered a strange bug or conflict involving jQuery, potentially the UI, and Bootstrap. If you'd like, you can take a look at the picture provided in the ...

loading times of Bootstrap-select are slow when used in multiples

I am facing performance issues on my website when I try to include more than 20 select options. The jQuery execution slows down significantly and there is a stop/continue alert, taking minutes to load. Is there any way to optimize the code for faster loadi ...

Tips on moving the inner rectangle within the outer rectangle

I am currently trying to center the innermost shape (the red shape) along the X-axis to the middle of the outermost shape (the black shape), while ensuring that the red shape remains within its direct parent, which is the blue shape. For instance, centeri ...

Develop a unique method for loading AngularJS templates

When working with AngularJS, there are various ways to provide an external template, such as using a script tag or a separate HTML file on the web server. However, I am faced with a situation where I need to implement a custom logic for retrieving these ...

Utilizing JSDoc for establishing an index signature on a class in ES6

When working with JSDoc, achieving the equivalent of Typescript's computed property names can be a challenge. In Typescript, you'd simply define it like this: class Test { [key: string]: whatever } This syntax allows you to access these comput ...

Vue.js is rejecting the date as invalid

I have encountered an issue with date errors in my .vue classes when uploading code to a SharePoint page. While using the Chrome debugging tool, I am seeing numerous date error messages like: Not a valid date: "2019-09-19T01:00:00Z" (see screenshot below) ...

What is the best method for interacting with multiple links in Puppeteer?

As a beginner with puppeteer, I am diving into the world of web scraping by attempting to create a simple scraping task. My Plan of Action The plan is straightforward: Visit a page, Extract all <li> links under a <ul> tag, Click on each < ...

Check and uncheck checkboxes in a hierarchical structure in real-time

I am facing a similar question to a previously solved issue regarding unchecking parent nodes if all children are unchecked using JQuery, but I am attempting to enhance the solution by ensuring that the children will also all uncheck if the parent is unche ...

Preventing default action within a passive event listener is not possible because the target is considered passive. This issue is particularly relevant with Three.js Track

I'm currently developing a 3D application using Three.js. One of the key components in this project is implementing a control system for the camera, which I have achieved using TrackballControls. However, as I tried to add an event listener, I encount ...

Executing a NodeJS function from a JavaScript function

I am working on a project involving Firebase and I am looking to connect a server-side function that can send an email to the client-side script. Below is my server-side index.js file: const functions = require('firebase-functions'); var nodema ...

What is the best way to highlight matching words from a list in a Django form's textarea using JavaScript?

I am working with the following form: class TestForm(Form): testfield = CharField(widget=Textarea(attrs={'rows': 10, 'id': 'test'}), label='Input test text here') Displayed in my template along with this context ...

Include the insertion button in the Tiny MCE Editor

Currently, I am in the process of developing my own plugin to integrate into the list of TinyMCE v4 plugins. So far, I have successfully added a button to the menu that opens a pop-up when clicked. In this pop-up, users can input data which is then added t ...

Address the snack bar problem

In my quest to create a custom snackbar, I have encountered a minor issue with setting and deleting session variables in Node.js. While using global or local variables works well for accessing data on the client side, there is a chance of issues when multi ...

Unable to retrieve user attributes (provided as res.locals.user) in express and hbs view

Here is a snippet of code I use to verify user tokens and store the user information in req.locals: exports.isLoggedIn = async (req, res, next) => { if (req.cookies.jwt) { try { const decoded = await promisify(jwt.verify)( ...

Tips for preserving state data post-page refresh in Nuxt3

When refreshing the page in Nuxt3, I am experiencing data loss in the state. Despite using localStorage and sessionStorage, the data is still being lost. Can anyone advise on how to maintain state data after a page refresh? Here is a snippet of my sourc ...

Once upon a time in the land of Storybook, a mysterious error message appeared: "Invalid version. You must provide a string

I keep encountering an issue while attempting to set up storybook. Can anyone help me figure out what's causing this problem? npx storybook@latest init • Detecting project type. ✓ TypeError: Invalid version. Must be a string. Got type "obje ...

How do I resolve the jQuery error "unable to find function url.indexOf" when working with Vide?

I had previously asked a question regarding the use of the Vide plugin for playing background videos on my website, which can be found here. However, I am now encountering an error that is puzzling me: https://i.stack.imgur.com/UDFuU.png I am unsure abo ...

`A straightforward technique for establishing client-server communication using NodeJS`

Stumbling upon a valuable code snippet on GitHub for enabling straightforward server-client communication in NodeJS has been quite enlightening. Upon making some adjustments, the finalized structure of my code looks like this: The client (Jade + Javascri ...

Identifying the HTML elements beneath the mouse pointer

Does anyone know the method to retrieve the HTML tag located directly under the mouse cursor on a webpage? I am currently developing a new WYSIWYG editor and would like to incorporate genuine drag and drop functionalities (rather than the common insert at ...

Having trouble with AngularJS validations?

Recently, I delved into AngularJS and began experimenting with the validations included in the framework. However, I encountered an issue as the validations don't seem to function: <div class="row"> <div class="col-xs-6"> < ...