How to Retrieve the Index of a Value within an Array in VUE.js

I am facing an issue where I want to update the status of tasks based on a certain method call. However, the challenge lies in obtaining the index of the specific item within the array in order to modify its status. Here is my HTML setup:

<div class="main" id="my-vue-app">
    <ul>
        <li v-for="task in completeTask">
            {{ task.description }} <button @click="markIncomplete">Mark as Incomplete</button>
        </li>

    </ul>
    <ul>
        <li v-for="task in incompleteTask">
            {{ task.description }} <button @click="markComplete">Mark as Complete</button>

        </li>
    </ul>
</div>

Additionally, here is the Vue script snippet:

<script>
    new Vue(
        {
            el: '#my-vue-app',
            data:
            {
                tasks: [
                {description:'go to market', status: true},
                {description:'buy book', status: true}, 
                {description:'eat biriani', status: true}, 
                {description:'walk half kilo', status: false}, 
                {description:'eat icecream', status: false}, 
                {description:'return to home', status: false}
                ]
            },
            computed: 
            {
                incompleteTask()
                {
                    return this.tasks.filter(task => ! task.status);
                },
                completeTask()
                {
                    return this.tasks.filter(task => task.status);
                }
            },
            methods: 
            {
                markComplete()
                {
                    // Logic to mark task as complete
                    return this.task.status = true;

                },
                markIncomplete()
                {
                    // Logic to mark task as incomplete
                    return this.task.status = false;
                }
            }
        }
    )
</script>

I am looking for a solution that enables me to utilize markComplete() and markIncomplete() effectively. The main roadblock I am facing is identifying how to access the index of the current element in order to adjust its status.

Answer №1

To find the index, you can add a second argument in the v-for loop:

<li v-for="(task, index) in incompleteTask">
    {{ task.description }} <button @click="markComplete(index)">Mark as Complete</button>
</li>
    methods: 
    {
        markComplete(index)
        {
            return this.tasks[index].status = true;

        },

Or for a potentially simpler approach, **pass the `task` directly**:
<li v-for="task in incompleteTask">
    {{ task.description }} <button @click="markComplete(task)">Mark as Complete</button>
</li>
    methods: 
    {
        markComplete(task)
        {
            return task.status = true;

        },

Answer №2

Read the Fine Manual (RTFM):

If you want to repeat a template element based on an Array of objects in Vue.js, you can utilize the v-repeat directive. Each object in the Array will create a child Vue instance with that object as its $data. These child instances inherit data from the parent, allowing access to properties from both instances. Additionally, you can use the $index property which represents the Array index of the rendered instance.

var demo = new Vue({
  el: '#demo',
  data: {
    parentMsg: 'Hello',
    items: [
      { childMsg: 'Foo' },
      { childMsg: 'Bar' }
    ]
  }
})
<script src="https://unpkg.com/vue/dist/vue.min.js"></script>

<ul id="demo">
  <li v-repeat="items" class="item-{{$index}}">
    {{$index}} - {{parentMsg}} {{childMsg}}
  </li>
</ul>

Source:

Note: The directive v-repeat is available in old versions of Vue.js :-)

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

Using Javascript to Manage Scroll Stop Events

I am currently facing a challenge while working on an IOS (Cordova) application. I am developing it using core Javascript without relying on any framework like Ionic or Onsen UI. The issue I am encountering is that I need to trigger an event when the scrol ...

Debugging a script designed to output a value of 1 if the Mean equals the Mode, and 0 if they are not equal

As a beginner coder, I am working on a code that should return 1 if the mean is equal to the mode and 0 otherwise. However, my current code only outputs 0 even when it should be returning 1. Any guidance or assistance in identifying where I may have made ...

anticipating the loading of component information

Currently, I am working on VueJS version 2 and have encountered an issue. When clicking on a link within componentA, it triggers the display of componentB which has the following structure: <template> <div> hey this is pokemon {{po ...

HTML elements not displaying in Ajax form

I am encountering an issue with my ajax based feedback form where the form is displaying the html from the response instead of processing it correctly. Here is the JQuery code: $(document).ready(function() { var form_holder = $('#form-holder'); ...

Is sending an AJAX request to a Node.js Express application possible?

Currently, I am attempting to authenticate before utilizing ajax to add data into a database $('#button').click(function () { $.post('/db/', { stuff: { "foo" : "bar"} }, callback, "json"); }); Below is my node.js code: ...

Convert your Airbnb short link into the full link

I am currently developing an application that utilizes Airbnb links as part of its input. So far, I have identified two types of links: Long form, for example: . These are commonly used on desktop. Short form, such as: . These shorter links are often shar ...

Map image showing only the tile layer in the top corner

My current project involves utilizing Ionic 5 and Vue.js. One of the screens in my project features a leaflet map that needs to cover most of the screen space. To implement this, I have integrated the Leaflet library for vue into my code. Here is a snippe ...

Implementing a filter in React with data fetched from MongoDB

Hey there! I'm encountering an issue while using the code in Project.jsx and ProductList.jsx. Every time I run the code, it gives me this error message: Warning: Each child in a list should have a unique "key" prop. Check the render method of Product ...

Issue with Fat-Free Framework and Abide AJAX form submission malfunction

Currently, I am utilizing Foundation 5.5.3 and Abide form validation in order to facilitate site registration. This is reflected in my Javascript code below: $('form#register').on('valid.fndtn.abide', function() { var data = { ...

Make sure to validate onsubmit and submit the form using ajax - it's crucial

Seeking assistance for validating a form and sending it with AJAX. Validation without the use of ''onsubmit="return validateForm(this);"'' is not functioning properly. However, when the form is correct, it still sends the form (page r ...

Experience the feeling of releasing momentum by click and dragging the scroll

One feature I am looking for is the ability to control the scroll speed when dragging, and have the scroll continue moving slightly after release instead of stopping instantly. CodePen: https://codepen.io/rKaiser/pen/qGomdR I can adjust the speed adequat ...

prompting the JavaScript hangman game to identify the letters in the "selected word"

Currently, I am on a mission to teach myself Javascript and have taken on the challenge of creating a simple hangman game. This type of project is commonly used in interviews or tests, so it seemed like a great opportunity for practice. My approach involve ...

Facing an issue with Heroku deployment where a React/Express app is encountering a 'Failed to load resource' error in the console while requesting the chunk.js files

Upon deploying my React application on Heroku, I encountered errors in the console. Refused to apply style from 'https://radiant-tor-66940.herokuapp.com/index.css' because its MIME type ('text/html') is not a supported stylesheet MIME ...

increasing the SQL integer value with padding

Is it possible to apply padding to certain INT return values retrieved from an SQL database using CSS within a div tag? I need specific numbers to have padding-left: 20px; while other specific numbers should have padding-right: 20px;. This presents a styl ...

The compass is currently not displaying the magnetometer values

Hello! I am currently working on a code that displays the values of the magnetometer's (x, y, z) components. Unfortunately, the issue I am facing is that the code keeps returning a "null" value continuously. You can find the link to my expo snack here ...

JavaScript: Responding to the fetch response based on certain conditions

I am currently working with a fetch() request that can either return a zip file (blob) or a JSON object in case of an error. The existing code successfully handles the zip file by sending it to the user's Downloads folder. However, when a JSON respons ...

What is a universal method to express "not yet interacted with" in Vue?

When I have an input field, I want to check the content before submitting it. Depending on whether the input is correct or incorrect, I apply a specific class for user feedback: new Vue({ el: "#app", data: { input: "" }, methods: { getCl ...

Is it possible to reuse a variable within a single HTML tag when using Angular 2?

I encountered a strange issue with Angular 2 that may be a bug. I noticed that I couldn't print the same variable in a template twice within the same HTML tag. When I tried to use the following code, it resulted in error messages. <div class=" ...

Confirmation for deletion in HTML form

Is there a way I can include a confirmation message for deleting an item on my form button? Any suggestions on which JavaScript code to use? <script type="text/javascript"> function confirmDelete() { return confirm("Are you sure you want to delete ...

How can we modify this function to interpret multiple selections at once?

For the task of displaying multiple selections from a scrolling list to an alert, I have implemented the following function: var toppings = ""; function displaySelectedToppings() { var topList = document.getElementById('to ...