代码之家  ›  专栏  ›  技术社区  ›  Hai Truong IT

Nuxtjs如何使用观察者查找在v-for中更改的索引

  •  0
  • Hai Truong IT  · 技术社区  · 2 年前

    我有一个示例代码,其中filteredDates是范围日期,timeOptionsByDate是范围从18:00到00:00

    <tr v-for="(date, index) in filteredDates" :key="date">
       <select v-model="formData.office_hour[index].time_from">
          <option v-for="time in timeOptionsByDate(date)" :value="time" :key="time">{{ time }}</option>
       </select>
       <select v-model="formData.office_hour[index].time_to">
          <option v-for="time in timeOptionsByDate(date)" :value="time" :key="time">{{ time }}</option>
       </select>
    </tr>
    

    论观察者

    watch: {
       'formData.office_hour': {
          deep: true,
          handler: 'handleOfficeHourChange',
        },
    }
    

    方法论

    handleOfficeHourChange(newVal, oldVal) {
       const index = this.findChangedIndex(newVal, oldVal)
    },
    findChangedIndex(newVal, oldVal) {
       for (let i = 0; i < newVal.length; i++) {
          if (!this.isEqual(newVal[i], oldVal[i])) {
             return i;
          }
       }
       return -1;
    },
    

    当我选择time_from时,time_to总是-1,错误的索引已经更改,如何更正上面的表达式

    0 回复  |  直到 2 年前
    推荐文章