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.