VueJS & VUEX: Shortening JS Code VueJS & VUEX: Shortening JS Code vue.js vue.js

VueJS & VUEX: Shortening JS Code


This is pseudo code for the most part. Somewhere store your common properties.

const props = ["time", "date", "event", "artist", "organizer", "location"]

Then use that in your functions.

function editEvent(state) {  // check to see if every property exists on the state  if (!props.every(p => state.form[p] !== '')) return  // build the event object  const event = props.reduce((acc, p) => acc[p] = state.form[p], {})  // I don't know where "events" comes from-- I left this alone  events.child(state.currentEventKey).update(event)  // clear each property  props.forEach(p => state.form[p] = '')  // clear your misc. props  state.currentEventKey = null  state.showForm = false}function populateEventForm(state, payload) {  props.forEach(p => state.form[p] = payload.event[p])  state.currentEventKey = payload.key  state.showForm = true}

Please be advised, since you posted this as a Vue/Vuex question, you may need to use Vue.set instead of an indexer in cases like the event object being built. It's hard for me to tell from the limited code you posted. In that case it would be something like

const event = props.reduce((acc, p) => {    Vue.set(acc, p, state.form[p])    return acc}, {})