user7331530
user7331530

Reputation: 985

Vue.js: Why is array resetting to its original state?

I am trying to read data from input and push the data to array: notes. I see it happening, but immediately after that notes resets to its original value: notes: [{title: 'Default Title', detail: 'Default Detail',},], Why is it happening? I can stop this by v-on:click.prevent="addNotes", but why is this happening?

<template>
  <div class="notes">
    <h1>{{ appTitle }}</h1>
    <form>
      <div class="form-group">
        <label for="noteTitle">Note title</label>
        <input
          type="text"
          class="form-control"
          id="noteTitle"
          placeholder="Enter note title"
          v-model="note.title"
        />
        <div class="form-group">
          <label for="noteDetail">Note Detail</label>
          <textarea
            type="text"
            class="form-control"
            id="noteDetail"
            placeholder="Enter Note Detail"
            v-model="note.detail"
          />
        </div>
        <button type="submit" class="btn btn-primary" v-on:click="addNotes">
          Submit
        </button>
        <div class="all-notes">
          <div class="each-note" v-for="(note, index) in notes" v-bind:key="index">
              <h2>{{note.title}}</h2>
          </div>
        </div>
      </div>
    </form>
  </div>
</template>
export default {
  data() {
    return {
      note: {
        title: '',
        detail: '',
      },
      notes: [
        {
          title: 'Default Title',
          detail: 'Default Detail',
        },
      ],
    };
  },
  methods: {
    addNotes() {
      const { title, detail } = this.note;
      debugger;
      this.notes.push({
        title,
        detail,
        date: new Date(Date.now()).toLocaleString(),
      });
    },
  },
  props: {
    appTitle: String,
  },
};

Upvotes: 0

Views: 109

Answers (1)

Eder D&#237;az
Eder D&#237;az

Reputation: 2071

It happens because the button is of type submit and it is inside a form. The default behaviour of a submit button is to post the data and then refresh the page. That's why your .prevent solution works, it stops the event from propagating and doesn't refresh the page keeping your state as it should be.

Upvotes: 1

Related Questions