我写了Vue组件,我使用v-model获取某些字段的值:一周打开和关闭时间
data(): {
return {
openingHours: [
{ day: 'open_mon', open: '', close: '', text: 'Monday'},
{ day: 'open_tue', open: '', close: '', text: 'Tuesday'},
{ day: 'open_wed', open: '', close: '', text: 'Wednesday'},
{ day: 'open_thurs', open: '', close: '', text: 'Thursday'},
{ day: 'open_fri', open: '', close: '', text: 'Friday'},
{ day: 'open_sat', open: '', close: '', text: 'Saturday'},
{ day: 'open_sun', open: '', close: '', text: 'Sunday'},
],
office: {
name: '',
description: '',
open_mon: '',
open_tue: '',
open_wed: '',
open_thurs: '',
open_fri: '',
open_sat: '',
open_sun: ''
}
我想写一个函数:
openingTime: function() {
this.office.open_mon = this.openingHours[0].open + '-' + this.openingHours[0].close
this.office.open_tue = this.openingHours[1].open + '-' + this.openingHours[1].close
this.office.open_wed = this.openingHours[2].open + '-' + this.openingHours[2].close
this.office.open_thurs = this.openingHours[3].open + '-' + this.openingHours[3].close
this.office.open_fri = this.openingHours[4].open + '-' + this.openingHours[4].close
this.office.open_sat = this.openingHours[5].open + '-' + this.openingHours[5].close
this.office.open_sun = this.openingHours[6].open + '-' + this.openingHours[6].close
}
然而它太长而且不好,因为它称同样的东西相同。如何重构动态设置名称变量并帮助缩短函数中的代码?感谢
答案 0 :(得分:0)
这可能会解决您的问题:
openingTime: function() {
this.openingHours.forEach(e => { // arrow function to prevent problems with this
this.office[e.day] = e.open + '-' + e.close
}
虽然您可能需要考虑重新调整数据,以便更好地适应。现在,它有点笨拙的结构,我会把关于日期的信息以日期的名称作为关键字扔出来,并将字符串作为计算对象,但我不知道你的具体应用。 / p>