VueJS& VUEX:缩短JS代码

时间:2017-06-09 15:56:44

标签: vue.js vuex

我喜欢简洁明了的代码。

所以我喜欢缩短这些javascript行,所以它们看起来并不那么混乱。

我的vuex变异代码:

1
                     A
2014-09-01 09:30:00  0
2014-09-01 09:31:00  1
3
                     A
2014-09-01 09:30:00  0
2014-09-01 09:33:00  3
5
                     A
2014-09-01 09:30:00  0
2014-09-01 09:35:00  6
6
                      A
2014-09-01 09:30:00   0
2014-09-01 09:36:00  12
8
                      A
2014-09-01 09:30:00   0
2014-09-01 09:38:00  15
16
                      A
2014-09-01 09:30:00   0
2014-09-01 09:46:00  21

又来了另一个:

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
  }
}

我怎样才能改善这一点?!??!

1 个答案:

答案 0 :(得分:4)

这在很大程度上是伪代码。某处存储您的共同属性。

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

然后在你的函数中使用它。

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
}

请注意,由于您将此作为Vue / Vuex问题发布,因此可能需要使用Vue.set代替索引器,例如event对象正在使用建成。我很难从您发布的有限代码中分辨出来。在那种情况下,它会像

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