Vuex can be quite repetitive to write generic mutations (arrays : set
, add
, update
, delete
, literals: update
) for each state property. But it's important to keep track of changes inside the store.
So here's a way to generate generic mutations and associated actions :
// book-store.js
const state = {
id: '',
title: '',
authors: [],
chapters: []
}
const mutations = {
...createArrayMutations('authors', 'chapters'),
...createLiteralMutations('id', 'title')
}
const actions = {
...createArrayActions('authors', 'chapters'),
...createLiteralActions('id', 'title')
}
How to use :
// array
store.dispatch('setAuthors', ['J. K. Rowling']) // state.authors : ['J. K. Rowling']
store.dispatch('addAuthors', 'Tolkien') // state.authors : ['J. K. Rowling', 'Tolkien']
store.dispatch('updateAuthors', {index: 1, value: 'J. R. R. Tolkien'}) // state.authors : ['J. K. Rowling', 'J. R. R. Tolkien']
store.dispatch('deleteAuthors', 1) // state.authors : ['J. K. Rowling']
// Literal
store.dispatch('updateId', '28') // state.id : '28'
Inspired by :