VueJS & VUEX: JS Code Abbreviation

I like clean and simple code.

So I like to cut these javascript lines so that they don't seem so cluttered.

My vuex mutation code:

editEvent(state) {
  if (
    state.form.time !== '' &&
    state.form.date !== '' &&
    state.form.event !== '' &&
    state.form.artist !== '' &&
    state.form.organizer !== '' &&
    state.form.location !== ''
  ) {
    const event = {
      time: state.form.time,
      date: state.form.date,
      event: state.form.event,
      artist: state.form.artist,
      organizer: state.form.organizer,
      location: state.form.location
    }
    events.child(state.currentEventKey).update(event)
    state.form.time = ''
    state.form.date = ''
    state.form.event = ''
    state.form.artist = ''
    state.form.organizer = ''
    state.form.location = ''
    state.currentEventKey = null
    state.showForm = false
  }
}

and here is another one:

populateEventForm(state, payload) {
  state.form.time = payload.event.time
  state.form.date = payload.event.date
  state.form.event = payload.event.event
  state.form.artist = payload.event.artist
  state.form.organizer = payload.event.organizer
  state.form.location = payload.event.location
  state.currentEventKey = payload.key
  state.showForm = true
}

How can I improve this?! ??!

+4
source share
1 answer

This is a pseudo code for the most part. Save your shared properties somewhere.

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

Then use this 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
}

Note that since you posted this as a Vue / Vuex question, you may need to use Vue.set instead of the indexer in cases, such as when building an object event. It's hard for me to say from the limited code that you posted. In this case, it will be something like

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

Source: https://habr.com/ru/post/1678889/


All Articles