从表到数据库的数据升级?

时间:2018-11-30 13:10:03

标签: javascript http post vue.js put

我有一个时间跟踪表Web应用程序,其中每一行代表数据库中的一个用户,每一列都有一个输入字段,用户将在其中输入特定日期的工作时间。 向您展示外观的小提琴:https://jsfiddle.net/L5u1fc0a/138/

基本上,如何确保仅将新数据发送到数据库。我希望(显然)在表中显示当前值,并且正在获取该数据并将其存储在Vue v-model中(请参见小提琴中的worklogs)-{{1}中的此数据}是填充表的内容。我的问题是我不知道该如何处理额外的时间。如果用户在特定日期再添加一个小时,然后点击“更新”(在小提琴中为“保存”),它将发送包含所有当前值和新值的整个worklogs数据值,因此如果某人仅添加一个输入,它将仍然发送worklogs对象中的所有内容。在小提琴中,如果您在某处输入新值并单击“保存”按钮,则可以看到我的数组worklogs也在填充所有现有值-如何仅将新更新的值发送到数据库?

1 个答案:

答案 0 :(得分:1)

如果要随时更改数据,就无法真正确定要更新的内容。您需要在工作时将它们分开,然后只保存updateData。因此,我将您的worklogs重命名为saved,并使updateData成为一个对象,该对象将保存与saved完全相同类型的条目。

我进行了合并savedupdateData的计算,并将其用于绑定的value。您不能在这里真正使用v-model,因为您不能将单个元素写回到计算字典中。但是您不需要。更改后,您更新updateData,并且value保持一致。

(请注意:如果您将每个输入都设为一个组件,则可以使用v-model,但是在父级中仍然有所有需要处理的管道。)

save函数执行后端调用的所有操作,更新saved,并清空updateData

/* app instance */
new Vue({
  el: '#app',
    data() {
    	const currentDate = new Date();
    	return {
      saved: {
        "1,2018-11-01": "8", 
        "1,2018-11-02": "8",
        "2,2018-11-03": "10",
        "2,2018-11-04": "10"
				},
      updateData: {},
      users: [
          {id: 1, firstName: 'Jay', lastName: 'Carter', email: 'jayz@rocafella.com'},
          {id: 2, firstName: 'Day', lastName: 'Darter', email: 'dayz@rocafella.com'}
        ],
        secondHalf: false,
        selectedYear: currentDate.getFullYear(),
        selectedMonth: currentDate.getMonth() + 1,
        
    };
  },
  methods: {
    prevPeriod() {
      if (!this.secondHalf) {
        this.selectedMonth -= 1;
        this.secondHalf = !this.secondHalf;
      } else {
        this.secondHalf = !this.secondHalf;
      }
      if (this.selectedMonth < 1) {
        this.selectedYear -= 1;
        this.selectedMonth = 12;
      }
    },
    nextPeriod() {
      if (this.secondHalf) {
        this.selectedMonth += 1;
        this.secondHalf = !this.secondHalf;
      } else {
        this.secondHalf = !this.secondHalf;
      }
      if (this.selectedMonth > 12) {
        this.selectYear += 1;
        this.selectedMonth = 1;
      }
    },
    getMonth(date) {
      const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
      return months[date.getMonth()];
    },
    getWeekDay(date) {
      const days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
    	return days[date.getDay()];
    },
    setUpdateData(userId, day, event) {
      const key = this.dataKey(userId, day);
      const value = event.target.value;
      
      if (this.saved[key] !== value) {
      	this.$set(this.updateData, key, value);
      } else {
      	this.$delete(this.updateData, key);
      }
    },
    save() {
			// Presumably, this would go somewhere that would refresh saved, but
      // the ultimate effect is just to copy the updateData into saved and
      // empty updateData
			Object.assign(this.saved, this.updateData);
      this.updateData = {};
		},
    dataKey(userId, day) {
    	return `${userId},${this.convertDateString(day)}`;
    },
    convertDateString(date) {
      let isoWithTimezone = new Date(
        date.getTime() - date.getTimezoneOffset() * 60000
      ).toISOString();
      return isoWithTimezone.split("T")[0];
    }
  },
  
  computed: {
  	allData() {
    	return Object.assign({}, this.saved, this.updateData);
    },
    getDates() {
      const year = this.selectedYear;
      const month = this.selectedMonth;
      
      let currentDate = new Date(year, month - 1, 1);
      const dates = [];
      
      while (currentDate.getMonth() == month - 1) {
        dates.push(currentDate);
        currentDate = new Date(
        	currentDate.getFullYear(),
          currentDate.getMonth(),
        	currentDate.getDate() + 1
        );
      }
      
      if (this.secondHalf) {
        return dates.slice(15);
      } else {
        return dates.slice(0, 15);
			}
    },
  }
})
input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
  -webkit-appearance: none;
  -moz-appearance: none;
  margin: 0;
}
<script src="https://unpkg.com/vue@latest/dist/vue.js"></script>
<div id="app">
  <div>
    <p>{{this.selectedYear}} - {{this.selectedMonth}}</p>
    <div>
      <button @click="prevPeriod"> ‹‹ </button>
      <button @click="nextPeriod"> ›› </button>
    </div>
    <div>
      <table id="conTab">
        <tr>
          <td></td>
          <td v-for="(date, key) in getDates" :key="key" style="font-size: 80%;"> {{getWeekDay(date)}}</td>
        </tr>
        <tr>
          <td style="border-top-width: 0px; border-left-width: 0px"></td>
          <td v-for="(date, key) in getDates" :key="key" style="font-size: 80%;"> {{getMonth(date)}} {{date.getDate()}}</td>
        </tr>
        <tbody>
          <tr v-for="(user, i) in users" :key="user.id">
            <td>
              {{user.firstName}}
            </td>
            <td v-for="(day, key) in getDates" :key="key">
              <input type="number" style="width: 35px;" :value="allData[dataKey(user.id, day)]" @change="setUpdateData(user.id, day, $event)">
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    <div><button @click="save">SAVE</button></div>
  </div>
  <pre>{{$data}}</pre>
</div>