【问题标题】:VueJS & VUEX: Shortening JS CodeVueJS 和 VueX:缩短 JS 代码
【发布时间】:2017-06-09 15:56:43
【问题描述】:

我喜欢简洁的代码。

所以我喜欢缩短这些 javascript 行,这样它们就不会显得那么混乱。

我的 vuex-mutation 代码:

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

这里还有一个:

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
}

我该如何改进?!??!

【问题讨论】:

标签: vue.js vuex


【解决方案1】:

这大部分是伪代码。在某个地方存储您的常用属性。

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 问题发布,您可能需要在构建 event 对象等情况下使用 Vue.set 而不是索引器。我很难从您发布的有限代码中分辨出来。在那种情况下,它会像

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

【讨论】:

    猜你喜欢
    • 2019-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多