When approaching repetitions in my code with Vue.js and Vuex, I often encounter similar mutations that need to be handled separately. For instance, I have mutations for both Services and Materials that share a lot of similarities.
The first mutation is for Services:
function setServiceItem(state, {model, value}) {
const service = state.order_services
service[model] = value
if (model === 'service') {
service.unit_price = value.price
}
updatePrice(service)
}
The second mutation is for Materials:
function setMaterialItem(state, {model, value}) {
const material = state.order_material
material[model] = value
if (model === 'material') {
material.unit_price = value.price
}
updatePrice(material)
}
Although these mutations are very similar, the constraints of Vuex limit my ability to merge them into a single mutation. One potential solution I considered was adding a third parameter like 'location' and handling them within a single function:
function setMisc(state, {model, value, location, eventForPriceAssignment}) {
const item = state[loc]
item[model] = value
if (model === eventForPriceAssignment) {
item.unit_price = value.price
}
updatePrice(material)
}
However, this approach would make the function more intricate and require passing additional parameters, negating the benefits of keeping the code DRY.