0

Всем привет)Я новенький в теме vue.js и мне нужна помощь в моём самообучении. У меня есть страница с формой где я могу создавать таски. Они добавляются в массив, а также этот массив сохраняется в localStorage. Вопрос в том как мне сделать редактирование выбранного таска. Сделать так что бы при нажатии на таск он появлялся в отдельном инпуте я сделал, а дальше остановился. Помогите советом ,если есть возможность то и примером, как мне изменить выбранный елемент массива.

const App = {
    data(){
        return{
            editInput:'',
            title:'Notes',
            input:{
                value:'',
                placeholder:'Type ur note'
            },
            notes:['task0','task1','task2']
        }
    },
    watch:{
        notes: {
            handler(updatedList) {
               localStorage.setItem('notes', JSON.stringify(updatedList));
            },
            deep: true,
        }
    },
    mounted() {
        this.getNotes();
    }
    ,
    methods:{
        info(note,index){
            this.editInput = note
        },
        getNotes(){
            const localNotes = localStorage.getItem('notes')
            if(localNotes){
                this.notes = JSON.parse(localNotes);
            }
        },
        onSubmit(){
            this.notes.push(this.input.value)
            this.input.value = ''
        },
        remove(index){

            this.notes.splice(index,1)
        }
    }
}

Vue.createApp(App).mount("#app");
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>#9 Notes</title>
    <script src="https://unpkg.com/vue"></script>
</head>
<body>
<div class="wrapper">
    <div id="app">
        <h1>{{title}}</h1>
        <form @submit.prevent="onSubmit">
            <input type="text" v-model="input.value" :placeholder="input.placeholder" required>
            <button>Add new Note</button>
        </form>
        <div class="notes">
            <div class="note" v-for="(note,index) in notes" :key="index">
                <p><span @click="info(note,index)">&#9998;</span><span @click="remove(index)">&#10005;</span>
                    {{note}}
                </p>
            </div>
        </div>
        <input type="text" v-model="editInput">
    </div>
</div>
<script src="app.js"></script>
</body>
</html>

1 ответ 1

0

Конкретно редактирование можно сделать вот так. Изменение массивов (точнее что относится к реактивности) описывается в документации Vue, а работа с самими массивами – в документации JS, или учебниках.

const App = {
  data() {
    return {
      editInput: '',
      title: 'Notes',
      input: {
        value: '',
        placeholder: 'Type ur note'
      },
      notes: ['task0', 'task1', 'task2'],
      editElement: {}, // Создаем переменную (свойство)
    }
  },
  watch: {
    notes: {
      handler(updatedList) {
        localStorage.setItem('notes', JSON.stringify(updatedList));
      },
      deep: true,
    }
  },
  mounted() {
    this.getNotes();
  },
  methods: {
    info(note, index) {
      this.editElement = {
        index,
        value: note
      } // Записываем данные, индекс элемента нам тоже нужно знать
    },
    update() {
      this.notes.splice(this.editElement.index, 1, this.editElement.value) // При сохранении записываем данные
      this.editElement = {} // Очищаем редактируемый элемент
    },
    getNotes() {
      const localNotes = localStorage.getItem('notes')
      if (localNotes) {
        this.notes = JSON.parse(localNotes);
      }
    },
    onSubmit() {
      this.notes.push(this.input.value)
      this.input.value = ''
    },
    remove(index) {

      this.notes.splice(index, 1)
    }
  }
}

Vue.createApp(App).mount("#app");
<!doctype html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>#9 Notes</title>
  <script src="https://unpkg.com/vue"></script>
</head>

<body>
  <div class="wrapper">
    <div id="app">
      <h1>{{title}}</h1>
      <form @submit.prevent="onSubmit">
        <input type="text" v-model="input.value" :placeholder="input.placeholder" required>
        <button>Add new Note</button>
      </form>
      <div class="notes">
        <div class="note" v-for="(note,index) in notes" :key="index">
          <p><span @click="info(note,index)">&#9998;</span><span @click="remove(index)">&#10005;</span> {{note}}
          </p>
        </div>
      </div>
      <!-- Проверяем, что переменная содержит не пустой объект -->
      <template v-if="Object.keys(editElement).length > 0">
        <input type="text" v-model="editElement.value">
        <button @click="update">Save</button>
      </template>

      <!-- Для наглядности -->
      {{ editElement }}
    </div>
  </div>
  <script src="app.js"></script>
</body>

</html>

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.