venom99
@venom99

Как возвращать значение поля input в исходное состояние после нажатия кнопки отмены?

Имеется список расписания занятий на определённую неделю, которые ведёт преподаватель. Преподаватель имеет возможность изменять значение в полях, после того как он кликает на определённое поле и начинает что-то вводить, появляется 3 соответствующие кнопки.
611e35f4beec4823814496.jpeg

В моём случае записи для таблицы приходят с бэка на страницу teacher и записываются в data на каждый день недели

teacher
import table_prepod from "@/components/table_prepod";

export default {
  name: "Teacher",

  components:{
  table_prepod
  },
  data() {
    return {
      id_prepod: 0, fio_prepod: "", name_predmet: "", id_user: "", now_time: new Date(""),
      Monday:[],
      Tuesday:[],
      Wednesday:[],
      Thursday:[],
      Friday:[]}
  },


после чего данные со страницы идут в компонент этой страницы c помощью props

table_prepod
<div id="content">
    <p class="p_table1">Понедельник</p><table cellspacing="0">
    <tr>
      <th>Время</th>
      <th>Группа</th>
      <th>Название предмета</th>
      <th>Тема</th>
      <th>Аудитория</th>
      <th>Д.З.</th>
    </tr>
    <tr  v-for="zan in Monday">
      <td v-for="zann in Array(zan)"><input v-on:input="monday_true += 1" v-model="zann[1]" class="input_table_prepod_time"></td>
      <td v-for="zann in Array(zan)"><input v-on:input="monday_true += 1" v-model="zann[2]" class="input_table_prepod_group"></td>
      <td v-for="zann in Array(zan)"><input v-on:input="monday_true += 1" v-model="zann[3]" class="input_table_prepod_namepred"></td>
      <td v-for="zann in Array(zan)"><input v-on:input="monday_true += 1" v-model="zann[4]" class="input_table_prepod_sub"></td>
      <td v-for="zann in Array(zan)"><input v-on:input="monday_true += 1" v-model="zann[5]" class="input_table_prepod_aud"></td>
      <td v-for="zann in Array(zan)"><input v-on:input="monday_true += 1" v-model="zann[6]" class="input_table_prepod_homew"></td>
    </tr>
  </table>
    <button v-if="monday_true" v-on:click="save(1)" class="button_table_prepod">Сохранить изменения</button>
    <button v-if="monday_true" v-on:click="deletee(1)" class="button_table_prepod2">Удалить изменённые записи</button>
    <button v-if="monday_true" v-on:click="back(1)" class="button_table_prepod3">Отмена изменений</button>
    <br>
    <p class="p_table2">Вторник</p>
    <table cellspacing="0">
      <tr>
        <th>Время</th>
        <th>Группа</th>
        <th>Название предмета</th>
        <th>Тема</th>
        <th>Аудитория</th>
        <th>Д.З.</th>
      </tr>
      <tr  v-for="zan in Tuesday">
        <td v-for="zann in Array(zan)"><input v-on:input="tuesday_true += 1"  v-model="zann[1]" class="input_table_prepod_time"></td>
        <td v-for="zann in Array(zan)"><input v-on:input="tuesday_true += 1"  v-model="zann[2]" class="input_table_prepod_group"></td>
        <td v-for="zann in Array(zan)"><input v-on:input="tuesday_true += 1"  v-model="zann[3]" class="input_table_prepod_namepred"></td>
        <td v-for="zann in Array(zan)"><input v-on:input="tuesday_true += 1"  v-model="zann[4]" class="input_table_prepod_sub"></td>
        <td v-for="zann in Array(zan)"><input v-on:input="tuesday_true += 1"  v-model="zann[5]" class="input_table_prepod_aud"></td>
        <td v-for="zann in Array(zan)"><input v-on:input="tuesday_true += 1"  v-model="zann[6]" class="input_table_prepod_homew"></td>
      </tr>
    </table>
    <button v-if="tuesday_true" v-on:click="save(2)" class="button_table_prepod">Сохранить изменения</button>
    <button v-if="tuesday_true" v-on:click="deletee(2)" class="button_table_prepod2">Удалить изменённые записи</button>
    <button v-if="tuesday_true" v-on:click="back(2)" class="button_table_prepod3">Отмена изменений</button>
    <br>
    <p class="p_table2">Среда</p><table cellspacing="0">
    <tr>
      <th>Время</th>
      <th>Группа</th>
      <th>Название предмета</th>
      <th>Тема</th>
      <th>Аудитория</th>
      <th>Д.З.</th>
    </tr>
    <tr  v-for="zan in Wednesday">
      <td v-for="zann in Array(zan)"><input v-on:input="wednesday_true += 1"  v-model="zann[1]" class="input_table_prepod_time"></td>
      <td v-for="zann in Array(zan)"><input v-on:input="wednesday_true += 1"  v-model="zann[2]" class="input_table_prepod_group"></td>
      <td v-for="zann in Array(zan)"><input v-on:input="wednesday_true += 1"  v-model="zann[3]" class="input_table_prepod_namepred"></td>
      <td v-for="zann in Array(zan)"><input v-on:input="wednesday_true += 1"  v-model="zann[4]" class="input_table_prepod_sub"></td>
      <td v-for="zann in Array(zan)"><input v-on:input="wednesday_true += 1"  v-model="zann[5]" class="input_table_prepod_aud"></td>
      <td v-for="zann in Array(zan)"><input v-on:input="wednesday_true += 1"  v-model="zann[6]" class="input_table_prepod_homew"></td>
    </tr>
  </table>
    <button v-if="wednesday_true" v-on:click="save(3)" class="button_table_prepod">Сохранить изменения</button>
    <button v-if="wednesday_true" v-on:click="deletee(3)" class="button_table_prepod2">Удалить изменённые записи</button>
    <button v-if="wednesday_true" v-on:click="back(3)" class="button_table_prepod3">Отмена изменений</button>
    <br>
    <p class="p_table2">Четверг</p><table cellspacing="0">
    <tr>
      <th>Время</th>
      <th>Группа</th>
      <th>Название предмета</th>
      <th>Тема</th>
      <th>Аудитория</th>
      <th>Д.З.</th>
    </tr>
    <tr  v-for="zan in Thursday">
      <td v-for="zann in Array(zan)"><input v-on:input="thursday_true += 1"  v-model="zann[1]" class="input_table_prepod_time"></td>
      <td v-for="zann in Array(zan)"><input v-on:input="thursday_true += 1"  v-model="zann[2]" class="input_table_prepod_group"></td>
      <td v-for="zann in Array(zan)"><input v-on:input="thursday_true += 1"  v-model="zann[3]" class="input_table_prepod_namepred"></td>
      <td v-for="zann in Array(zan)"><input v-on:input="thursday_true += 1"  v-model="zann[4]" class="input_table_prepod_sub"></td>
      <td v-for="zann in Array(zan)"><input v-on:input="thursday_true += 1"  v-model="zann[5]" class="input_table_prepod_aud"></td>
      <td v-for="zann in Array(zan)"><input v-on:input="thursday_true += 1"  v-model="zann[6]" class="input_table_prepod_homew"></td>
    </tr>
  </table>
    <button v-if="thursday_true" v-on:click="save(4)" class="button_table_prepod">Сохранить изменения</button>
    <button v-if="thursday_true" v-on:click="deletee(4)" class="button_table_prepod2">Удалить изменённые записи</button>
    <button v-if="thursday_true" v-on:click="back(4)" class="button_table_prepod3">Отмена изменений</button>
    <br>
    <p class="p_table2">Пятница</p><table cellspacing="0">
    <tr>
      <th>Время</th>
      <th>Группа</th>
      <th>Название предмета</th>
      <th>Тема</th>
      <th>Аудитория</th>
      <th>Д.З.</th>
    </tr>
    <tr  v-for="zan in Friday">
      <td v-for="zann in Array(zan)"><input v-on:input="friday_true += 1"  v-model="zann[1]" class="input_table_prepod_time"></td>
      <td v-for="zann in Array(zan)"><input v-on:input="friday_true += 1"  v-model="zann[2]" class="input_table_prepod_group"></td>
      <td v-for="zann in Array(zan)"><input v-on:input="friday_true += 1"  v-model="zann[3]" class="input_table_prepod_namepred"></td>
      <td v-for="zann in Array(zan)"><input v-on:input="friday_true += 1"  v-model="zann[4]" class="input_table_prepod_sub"></td>
      <td v-for="zann in Array(zan)"><input v-on:input="friday_true += 1"  v-model="zann[5]" class="input_table_prepod_aud"></td>
      <td v-for="zann in Array(zan)"><input v-on:input="friday_true += 1"  v-model="zann[6]" class="input_table_prepod_homew"></td>
    </tr>
  </table>
    <button v-if="friday_true" v-on:click="save(5)" class="button_table_prepod">Сохранить изменения</button>
    <button v-if="friday_true" v-on:click="deletee(5)" class="button_table_prepod2">Удалить изменённые записи</button>
    <button v-if="friday_true" v-on:click="back(5)" class="button_table_prepod3">Отмена изменений</button>
  </div>

  </body>
</template>

<script>

export default {
  data(){
    return{
      monday_true: 0,
      tuesday_true: 0,
      wednesday_true: 0,
      thursday_true: 0,
      friday_true: 0,
    }
  },
  props:{

    Monday:{
      type: Array,
      required: true
    },
    Tuesday:{
      type: Array,
      required: true
    },
    Wednesday:{
      type: Array,
      required: true
    },
    Thursday:{
      type: Array,
      required: true
    },
    Friday:{
      type: Array,
      required: true
    },
  },
  methods:{
    deletee(){


    },

    back(A){
      if (A===1){
        this.monday_true = 0
      }
      if (A===2){
        this.tuesday_true= 0
      }
      if (A===3){
        this.wednesday_true = 0
      }
      if (A===4){
        this.thursday_true = 0
      }
      if (A===5){
        this.friday_true = 0
      }


    },

    save(){

    },


  },
  name: "table_prepod",

}
</script>


В котором требуется реализовать 3 функции: save, back, delete. На данный момент я не понимаю как полноценно реализовать функцию back, которая отвечает за кнопку "отмена изменений", сейчас при нажатии на кнопку, все кнопки переходят в исходное состояние и не отображаются на экране как это было до ввода какой-либо информации пользователем в то или иное поле, а возвращение значений полей в исходное состояние реализовать не удалось. Заранее благодарю за помощь, был бы признателен за подсказку по реализации остальных кнопок.

Данные для примера:
Данные которые приходят с бэка в массив Monday:
611e47ac50d96958334199.jpeg

[1, "2021-02-01 08:15:00", "21-Э-95", "Проектирование баз данных", "Тема", 1, "Д.З."]
[1, "2021-02-01 09:55:00", "11-А-96", "Проектирование баз данных", "Тема", 2, "Д.З."]
[1, "2021-02-01 11:35:00", "13-С-94", "Проектирование баз данных", "Тема", 3, "Д.З."]
  • Вопрос задан
  • 191 просмотр
Решения вопроса 1
@ajderha
Компонент - teacher

<template>
  <div>
    <table_prepod
      v-for="(value, key) in dayNames"
      :key="key"
      ref="table_prepod"
      :dayName="value"
      :dayData="daysData[key]"
      @save="onSave($event, key)"
      @remove="onRemove($event, key)"
    />
  </div>
</template>

<script>
import table_prepod from "./table_prepod";

const dayNames = {
  Monday: 'Понедельник',
  Tuesday: 'Вторник' // и т.д.
}

export default {
  components:{
  table_prepod
  },
  data() {
    return {
      dayNames,
      id_prepod: 0, fio_prepod: "", name_predmet: "", id_user: "", now_time: new Date(""),
      daysData: {
        Monday: [
          [1, "2021-02-01 08:15:00", "21-Э-95", "Проектирование баз данных", "Тема", 1, "Д.З."],
          [1, "2021-02-01 09:55:00", "11-А-96", "Проектирование баз данных", "Тема", 2, "Д.З."],
          [1, "2021-02-01 11:35:00", "13-С-94", "Проектирование баз данных", "Тема", 3, "Д.З."]
        ],
        Tuesday:[],
        Wednesday:[],
        Thursday:[],
        Friday:[]
      }
    }
  },
  methods: {
    // async
    onSave(data, dayName) {
      console.log('onSave::data', data.model)
      console.log('onSave::dayName', dayName)
      // await saving
      this.daysData[dayName] = data.model
      // then
      data.cb()
    },
    // async
    onRemove(data, dayName) {
      console.log('onDelete::data', data.rowsIndex)
      console.log('onDelete::dayName', dayName)
      // await saving
      this.daysData[dayName] = this.daysData[dayName].filter((_, i) => !data.rowsIndex.includes(i))
      // then
      data.cb()
    }
  }
}
</script>


Компонент - table_prepod
<template>
  <div>
    <p class="p_table1">{{ dayName }}</p>
    <table cellspacing="0">
      <tr>
        <th>Время</th>
        <th>Группа</th>
        <th>Название предмета</th>
        <th>Тема</th>
        <th>Аудитория</th>
        <th>Д.З.</th>
      </tr>
      <tr v-for="(row, rowIndex) in model" :key="row[1]">
        <td
          v-for="(field, index) in row.filter((_, i) => (i !== 0))"
          :key="`${field}-${index}`"
        >
          <input
            v-model="row[index]"
            @input="onInputField(rowIndex, index, $event.target.value)"
          />
        </td>
      </tr>
    </table>

    <div v-if="changedRowsIndex.length">
      <button v-on:click="save()">Сохранить изменения</button>
      <button v-on:click="remove()">Удалить изменённые записи</button>
      <button v-on:click="back()">Отмена изменений</button>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    dayName: {
      type: String,
      default: "",
    },
    dayData: {
      type: Array,
    },
  },

  data() {
    return {
      model: [],
      changedRowsIndex: []
    };
  },

  watch: {
    dayData: {
      immediate: true,
      deep: true,
      handler(to) {
        this.setModel();
      },
    },
  },

  methods: {
    setModel() {
      this.model = this.dayData.map((x) => x.map((y) => y));
    },
    back() {
      this.setModel();
      this.changedRowsIndex = []
    },
    onInputField(rowIndex, fieldIndex, value) {
      if (this.dayData[rowIndex][fieldIndex] !== value) {
        if (this.changedRowsIndex.indexOf(rowIndex) === -1) {
          this.changedRowsIndex.push(rowIndex)
        }
      } else {
        const isRowChanged = this.dayData[rowIndex].map((x, i) => x === this.model[rowIndex][i]).some((x) => !x)
        if (!isRowChanged) {
          this.changedRowsIndex = this.changedRowsIndex.filter((i) => i !== rowIndex)
        }
      }
    },
    clearChanges() {
      this.changedRowsIndex = []
    },
    save() {
      // если нужно - выкидываем наверх
      this.$emit("save", {
        model: this.model,
        cb: () => this.clearChanges()
      });
      // либо из этого компонента отправляем - тогда затем this.clearChanges()
    },
    remove() {
      // если нужно - выкидываем наверх
      this.$emit('remove', {
        rowsIndex: this.changedRowsIndex,
        cb: () => this.clearChanges()
      })
      // либо из этого компонента отправляем - тогда затем this.clearChanges()
    }
  },
};
</script>
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы