"Implementing a feature where users can select multiple items by checking checkboxes, then storing the selected items in an array

In the application I'm working on, there is an array of items being displayed with checkboxes. I want to bind the state of these checkboxes (checked/unchecked) to a Vuex store in order to keep track of selected items.

Snippet of Vuex action code:

const actions: Actions = {
    changeCheckProducts({ state, commit, dispatch }, payload) {
    const { value, data } = payload
    const index = state.products.findIndex(
      item => item.id === data.id
    )
    if (index === -1) {
      return
    }
    commit('CHANGE_CHECK_PRODUCTS_DETAILS', { index, value })
    dispatch('addSelectedItems', { data })
  },
  addSelectedItems({ commit, state }, payload) {
    // Need help with adding selected items to a new array in state
    state.newArray.push(payload.id)
    commit('ADD_SELECTED_ITEMS', payload)
  },
}

Snippet of store mutation code:

const mutations: Mutations = {
    CHANGE_CHECK_PRODUCTS_DETAILS(state, payload) {
    const { index, value } = payload
    state.products[index].checked = value
  },
  ADD_SELECTED_ITEMS(state, payload) {
    // Implement logic to add selected items to a new array in state
  },
}

Snippet of component code:

<ul>
  <li aria-expanded="false"
    v-for="file in products"
    :key="file.id">
    <span>
      <input type="checkbox"
             :id="file.id"
             :value="file.id"
             v-model="checkedItems"
             @change="onSelectedItems"/>
      <span class="doc_input">
        <i class="el-icon-document" aria-hidden="true"></i>
      </span>
      <span class="product__name">
        {{file.name}}
      </span>
    </span>
  </li>
</ul>

Methods:

onSelectedItems(data) {
    this.$store.dispatch('changeCheckProducts', data)
}

I've been struggling to correctly implement the functionality of storing checked items and updating the array accordingly when items are unchecked or checked. As a newcomer to Vuex, any guidance on resolving the issues in my store implementation would be greatly appreciated.

Answer №1

To update the function, make the following changes:

onSelectedItems() {
  this.$store.dispatch('updateCheckedProducts', this.checkedItems)
  // this.checkedItems contains product IDs [1, 2, 3] for selected items
}

Update your Vuex store:

updateCheckedProducts({ commit }, payload) {
    commit('UPDATE_CHECKED_PRODUCTS_DETAILS', payload)
    ...
}

...

// Mutations should handle state changes.
UPDATE_CHECKED_PRODUCTS_DETAILS(state, payload) {
    state.products.forEach(product => {
        if (payload.indexOf(product.id) > -1) {
            product.checked = true
        }
    })
},

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

The function Model.find({}) is coming back as empty despite the fact that there are records present in the

While I can successfully add data to the users collection using my '/sign-up' route, I'm facing an issue with reading all the documents from the users collection. Instead of the expected data, all I receive is an empty array. { "status": ...

Using JavaScript functions on HTML data loaded by the jQuery.append() method: A guide

Utilizing JSON data, I have successfully generated HTML content representing Questions and Multiple Choice Questions. My next goal is to capture user responses in an array after the submit button is clicked. This involves storing which radio button the use ...

Using jQuery to create a script that will transition random images simultaneously within a div

I am currently working on a JavaScript script that will animate 10 images flying into a div, appearing side by side. The goal is to have each image fly in randomly with a unique transition. At the moment, my script is almost complete as I've successf ...

Utilizing base classes in callbacks with ES6 in NodeJS

Consider this scenario where I have a class as shown below: class X extends Y { constructor() { super(); } method() { asyncMethod( function( err ) { super.method( err ); } ); } } The issue here is that super actually ...

Can you provide guidance on displaying flash messages in my template using Express.js?

app.get('/',function(req,res){ res.render('home'); // Ensure the template has access to the flash message }); app.get('/go',function(req,res){ req.flash("info", "You have gone to GO and got redirected back home!"); ...

Altering various HTML components with every swipe of SwiperJS

I am new to working with JavaScript and I have integrated a Swiper JS element into my HTML page. Here is the current code I am using: <head> <link rel="stylesheet" href="https://unpkg.com/swiper/swiper-bundle.min.css&quo ...

Adding Javascript and CSS files to the document dynamically

I've created a custom jQuery plugin, but I need it to verify if jQuery is already loaded. If not, I want the plugin to load jQuery along with a few other necessary JavaScript files. Additionally, I want it to check if a specific CSS file has been load ...

Why do confirm or alert boxes in Safari on Windows require a double click?

I'm currently working on a simple JavaScript example where I want to display an alert box when an HTML button is clicked in SAFARI. However, I've noticed that it requires a double click to make the alert disappear from the screen. Does anyone ha ...

Storing data from multiple children and triggering a parent component function in Vue: A guide

In my Messaging Tool component, I have several child components that make up the messaging tool interface. You can see the visual representation of these components here: https://i.stack.imgur.com/JoEko.png There are 3 channels within the tool, each openi ...

Having trouble generating a Vue project using vue/cli?

I am currently developing a vuex application using Vue CLI. Unfortunately, the CLI gets stuck during metadata fetching (<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="eb88838480828f8a99abd9c5dac5dd">[email protected]</a& ...

Codeigniter Autocomplete Feature with Ajax - Page Not Found Error

I am currently facing an issue while porting a working php application with AutoSuggest JS to CodeIgniter. My expertise in CI is not very strong which is why I ventured into this task. The problem lies in the fact that it is not functioning as expected. Be ...

Drag and Drop Functionality in ReactJS for Organizing Multiple Lists

After hours of searching, I have yet to find a React library that can handle sorting between multiple lists. The closest solution I came across was in this article: There is also an example provided here: The issue with this solution is that you have to ...

Autocomplete component fails to trigger onChange event upon losing focus in Mui framework

When using a Mui Autocomplete with the properties of multiple and freeSolo, a situation arises where pressing Return triggers an onChange event. However, when tabbing out of the Autocomplete widget, the typed text remains without updating the state of the ...

Steps for importing a jQuery script into a Vue component

Looking to include a basic jQuery script in my Vue file. Attempted to import it using the following method: In the Vue file import {myScript} from "@/components/scripts/myScript.js" Then in the myScript.js file : export const myScript = { $('.cl ...

Receiving the [object HTMLInputElement] on the screen rather than a numerical value

I have an input box where a user can enter a number. When they click a button, I want that number to be displayed on the page. However, instead of seeing the number, I am getting the output as [object HTMLInputElement]. Below is my TypeScript code: let qu ...

Learn the process of applying distinct CSS classes to various elements within an AJAX response

The client initiates an AJAX call via jQuery. Upon fetching data from the database, I return the response which includes the application of numerous classes and styles to various HTML tags. Unfortunately, this process results in code that appears unsightly ...

"React-router is successfully updating the URL, however, the component remains un

I am currently working on a React application that includes a form for users to fill out. Once the user clicks the submit button, I want them to be redirected to a completely different page. Although I have only focused on the visual design at this point a ...

React router will only replace the last route when using history.push

I'm working on implementing a redirect in React Router that triggers after a specific amount of time has elapsed. Here's the code I've written so far: submitActivity(){ axios.post('/tiles', { activityDate:thi ...

Is there a way to conclude an Inquirer prompt depending on the response received?

My current project involves creating an application that presents a series of questions to gather information and generate an employee profile. This application is designed to be recursive, meaning that users will have the option to exit and terminate the ...

Issue with event.preventDefault() in Jquery not functioning as expected

My goal is to have the menu display and hide list items on click, with them being hidden by default. However, the issue I am facing is that the menu is generated in the admin section, so it automatically assigns a URL to each item. If I set the URL field o ...