Home > OS >  After commit, variable is still reactive
After commit, variable is still reactive

Time:01-15

I'm trying to commit a new task.

The expected result should be 'created task with title' but the title is empty because 'formData' is still reactive.

Here is code example:

// index.vue
<form  @submit.prevent="createTask()">
  <label >
    Title:
    <input
      type="text"
       
      v-model="formData.title"
      placeholder="Title"
      required
    />
    </label>
  <button type="submit" >Create</button>
</form>

...

export default class App extends Vue {
  formData = {
    title: "",
    completed: false,
  };


  createTask(): void {
    store.commit("task/SET_TASK", this.formData);
    this.formData.title = "";
  }
}

// Task.ts (vuex)
export default class Task extends VuexModule {
  tasks = [
    {
      title: "Example task",
      completed: false,
    },
  ];

  @Mutation
  SET_TASK(payload: TaskInterface) {
    this.tasks.push(payload);
  }
}

What I'm doing wrong?

CodePudding user response:

You can circumvent this by creating a new object using the spread syntax.

createTask(): void {
    store.commit("task/SET_TASK", { ...this.formData });
    this.formData.title = "";
  }
  •  Tags:  
  • Related