Ways to update an object's property within a loop by leveraging a checkbox in Vuex

I have a module called todosModule that stores necessary state information. The todos array holds objects, and when I iterate through them in a loop, I want the completed property of a specific object to change when the checkbox state changes.

The completed property is boolean.

Below is the content of the todosModule.js file for Vuex store:


import axios from "axios";
export const todosModule = {
    state: () => ({
        todos: [],
        page: 1,
        limit: 10,
        totalPages: 0,
        isTodosLoading: false
    }),
    getters: {

    },
    mutations: {
        setTodos(state, todos) {
            state.todos = todos;
        },
        setPage(state, page) {
            state.page = page;
        },
        setTotalPages(state, totalPages) {
            state.totalPages = totalPages;
        },
        setLoadingTodos(state, bool) {
            state.isTodosLoading = bool;
        },
        setCompleted(state, completed) {
            console.log(state.todos.completed);
            state.todos.completed = completed;
        }

    },
    actions: {
        async fetchTodos({state, commit}) {
            try {
                commit('setLoadingTodos', true);
                const response = await axios.get('https://jsonplaceholder.typicode.com/todos', {
                    params: {
                        _page: state.page,
                        _limit: state.limit
                    }
                });
                commit('setTotalPages', Math.ceil(response.headers['x-total-count'] / state.limit));
                commit('setTodos', response.data);
            } catch (e) {
                console.log(e);
            } finally {
                commit('setLoadingTodos', false);
            }
        }
    },
    namespaced: true
}

Below is the code for TodoItem.vue:


<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<template>
  <div class="col">
    <div class="card">
      <div class="card-body" :class="todo.completed ? 'bg-light' : ''">
        <div class="d-flex align-self-center justify-content-between">
          <h5 class="card-title">{{todo.title}}</h5>
          <div class="form-check form-switch">
            <input class="form-check-input" type="checkbox" id="flexSwitchCheckChecked" @change="setCompleted" :checked="todo.completed">
          </div>
        </div>
        <p v-if="todo.completed === true" class="card-text text-success">Completed</p>
        <p v-else class="card-text text-danger">Not Completed</p>
        <div class="d-flex align-content-center justify-content-between">
          <div class="btn-list">
            <button-bootstrap css-class="btn-primary">Edit</button-bootstrap>
            <button-bootstrap css-class="btn-danger">Delete</button-bootstrap>
          </div>
          <div class="card-date d-inline-flex text-muted">
            <span class="align-self-center">ID: {{todo.id}}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import ButtonBootstrap from "@/components/UI/ButtonBootstrap";

export default {
  name: "TodoItem",
  components: {ButtonBootstrap},
  props: {
    todo: {
      type: Object,
      required: true
    }
  },
  methods: {
    setCompleted(event) {
      this.$store.commit('todos/setCompleted', event.target.checked);
    },
  }
}
</script>

<style lang="scss" scoped>
.form-switch .form-check-input {
  margin-left: 0;
}
.btn-list {
  button:first-child {
    margin-right: 1rem;
  }
}
</style>

Parent file TodoList.vue:


<template>
<div class="row row-cols-1 g-4">
  <TodoItem v-for="todo in todos" :todo="todo" :key="todo.id"/>
</div>
</template>

<script>
import TodoItem from "@/components/TodoItem";
export default {
  name: "TodoList",
  components: {TodoItem},
  props: {
    todos: {
      type: Array,
      required: true,
    }
  }
}
</script>

<style lang="scss" scoped>
.row {
  margin-top: 2rem;
}
</style>

Could someone please help me with changing a specific property of a particular object?

UPDATE! I found a solution!


setCompleted(state, completed) {
    const index = state.todos.findIndex(todo => todo.id === completed.id);
    state.todos[index].completed = completed.completed;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

Answer №1

To add an extra attribute to the method, simply pass it in

<input class="form-check-input" type="checkbox" id="flexSwitchCheckChecked" @change="setCompleted($event, todo.id)" :checked="todo.completed">

Then, in the setCompleted function, make the following modification

setCompleted(event, id) {
  this.$store.commit('todos/setCompleted', {completed: event.target.checked , id: id})
},

In your todoModules.js file, update the setCompleted mutation as shown below

setCompleted(state, payload) {
  const index = state.todos.findIndex(todo => todo.id === payload.id);
  state.todos[index].completed = payload.completed;
}

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

Encountering Issues with NextJS Dynamic SSR: Mobile Devices stuck on loading screen

Issue: The dynamic import feature of Next JS is encountering loading issues specifically on mobile browsers such as Google Chrome and Safari on IOS. Strangely, the functionality works smoothly on desktop browsers like Google Chrome and Mozilla. The projec ...

Trigger a function upon clicking a DOM element in Vue.js

My goal is to trigger a function whenever I click on elements in the DOM that have a specific class. Despite my efforts, the functionality doesn't seem to work, and no errors are being reported. Here's the relevant code: methods: { ...

Tips for dynamically adjusting price values in Magento

As someone new to Magento, I am looking to update the price value on a product's detail page dynamically using Ajax. Additionally, I would like this updated price to reflect in the cart page as well. To see an example of what I'm trying to achie ...

Steps to display the leave site prompt during the beforeunload event once a function has finished running

While facing a challenge with executing synchronous Ajax methods in page dismissal events, I discovered that modern browsers no longer support this functionality in the "beforeunload" event. To work around this issue, I implemented a new promise that resol ...

unit testing of v-slot in vue.js with a function invocation

During my testing of the desired component, I utilized bootstrap-vue as the css framework for vue.js. The component in question incorporates b-table and features a v-slot with a call function. <template> <b-table striped borde ...

Ways to incorporate an increment indicator into a JavaScript slider

I am currently using the Angular-Slider created by Prajwalkman, which you can find at THIS LINK. Nevertheless, I am in need of adding indicators with specific values. To illustrate this, I have prepared a proof of concept that can be viewed below. Ideally ...

Create a responsive canvas with custom shapes

After designing a canvas with a gradient-filled circle, I encountered a challenge in making the canvas and the circle responsive to varying screen sizes. Initially, I attempted to use `vh` and `vw` units for the width and height of the canvas. However, ad ...

Utilize the <a> element as a button to submit the data form

I am looking to transfer data from a form to another PHP page without using a button within the form itself. Instead, I have placed a separate button outside of the form for submission. How can I achieve this by sending the form data to the other page? Bel ...

utilizing AJAX to retrieve scripts from WITHIN my own domain

In the realm of ajax scripts, I encounter a scenario where referencing something within the same domain requires passing HTML and associated javascript. Due to it being a non X-domain setup, I anticipate that this could be achievable. The aim here is to fe ...

Sending a PDF document to a function that specifically calls for a file location or URL

Currently, I am developing a web application for an online library where I need to extract metadata from PDF files that are uploaded. To achieve this, I am utilizing the nodejs libraries pdf.js-extract and multer-gridfs-storage for file uploads. However, I ...

What is the best way to retrieve a row in ui-grid using data from a specific column?

I am currently utilizing the ui-grid feature provided by . I have been experimenting with various methods, but due to my recent introduction to Angular, I find the documentation quite perplexing. I have implemented a custom search tag system and my goal i ...

Dynamically include properties to href tag

Here is how I populate a list: menu += "</div><div class='col-xs-6'>" menu += "<p class='t06'><a href=" + items[item].Enlace + ">" + items[item].Title + "</a></p>"; To achieve what I want, w ...

optimal method for displaying HTML strings with components in Vue

My website is a Blog/News site featuring posts that contain HTML content stored in the database. In addition to posts, I also want to include elements like sliders which cannot be generated using v-html. I explored Vue's Render Functions to find a so ...

Using AJAX for fetching and saving an object into a variable

I am dealing with two specific files in my project. The first one is called index.php, where the user initiates an AJAX request. The second one is called process.php, which is responsible for sending data back to the index.php file. function AjaxResponse( ...

Exploring the functionality of dynamic routing with Vue.js

Here is my JSON object where I am trying to access the jackets in my URL: { "_id": "6316f215fd9c107baa1bc160" "type": "Jackets", } Below is my router component used to get the product by ID: { path: " ...

When developing in vue.js and preparing for production, I encounter a 404 error with certain files located within the static folder, despite the fact that the URLs are accurate

As I prepare my application for production, I have encountered an issue. While everything works perfectly in the development environment, upon building and uploading the application to the server, only the HTML, Javascript, some CSS, and a few files load. ...

Using Laravel and Vue.js to Add Data to an Array

I have an array that needs to be inserted as new records in a database table along with the id of another table. How can I modify the store function to loop through each item in the array, grab the id from the other table, and insert them into the database ...

Display cautionary message upon the deletion of a row from a gridview in asp.net

I have implemented a gridview on my web form that includes a command field for delete and edit functionalities. My goal is to display a javascript alert message when a user clicks on the delete button: Are you sure you want to delete this record? If t ...

Filtering data at different levels in Javascript/Javascript programming language

Consider this array: var selection = ["14-3","19-5", "23-5", "40-8", "41-8"]; We now have two separate arrays: Array1 includes the first part of each value (before hyphens) in the original array, such as 1 ...

AngularJS: How to Implement Multi-select Functionality with Bootstrap Typeahead

I'm currently implementing bootstrap multiselect in my angular project (Bootstrap 2.3) My goal is to achieve a similar functionality using bootstrap typeahead, allowing users to select multiple values from search results. I've tried using the h ...