Vue.js VueJS&;VUEX:缩短JS代码
我喜欢干净简单的代码 所以我喜欢缩短javascript的这些行,这样它们就不会显得那么杂乱了 我的vuex变异代码:Vue.js VueJS&;VUEX:缩短JS代码,vue.js,vuex,Vue.js,Vuex,我喜欢干净简单的代码 所以我喜欢缩短javascript的这些行,这样它们就不会显得那么杂乱了 我的vuex变异代码: editEvent(state) { if ( state.form.time !== '' && state.form.date !== '' && state.form.event !== '' && state.form.artist !== '' && state
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
}
我怎样才能改进这个 这大部分是伪代码。在某个地方储存你的共同财产
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问题发布,在生成事件
对象等情况下,您可能需要使用索引器而不是索引器。从你发布的有限代码我很难分辨。如果是那样的话,它会是这样的
const event = props.reduce((acc, p) => {
Vue.set(acc, p, state.form[p])
return acc
}, {})
这属于更多的人。