[Vuejs]-Add/Edit list item at parent from child component form

0👍

I tried to solve your problem. To do this I modified and in some places simplified your code to keep only what was close to the SaveNewIgredient() function. So here is my code.

Parent Component (for me App.vue):

<template>
  <AddItemsForm @addIngredient="SaveNewIgredient" />
</template>

<script>
import AddItemsForm from "./AddItemsForm"; //Child Component

export default {
  name: "App",
  components: { AddItemsForm },
  data() {
    return {
      article: {
       igredients: [], //List to add/edit item at AddItemsForm child component
      },
      editedIgredient: {
        //Item to use for editing or adding new item to article.igredients
        title: "",
        subIgredients: [],
      },
      defaultItem: {
        //Item used for resetting editedIgredient item
        title: "",
        subIgredients: [],
      },
    };
  },
  methods: {
    SaveNewIgredient(newItem) {
      console.log("Received: ", newItem);

      this.editedIgredient = newItem;
      this.article.igredients.push({ ...this.editedIgredient });
      console.log("defaultClear: ", this.defaultItem);
      console.log("infoItem: ", this.editedIgredient);

      this.editedIgredient = this.defaultItem;

      console.log("defaultClear: ", this.defaultItem);
      console.log("editedWillClear: ", this.editedIgredient);
      console.log("listFinal: ", this.article.igredients);
    },
  },
};
</script>

Child Component (for me AddItemsForm.vue):

<template>
  <div>
    <input v-model="newIgredient" placeholder="New Igredient" />
    <button @click="addNewIgredient">ADD</button>
    <div>
      <button color="primary" @click="AddIngredients">Save</button>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    IngredientsItem: {
      type: Object,
      default() {
        return {
          title: "",
          subIgredients: [],
        };
      },
    },
  },
  data() {
    return {
      newIgredient: "",
      title: "TEST",
      titleNbr: 0,
      resetIgredient: false,
    };
  },
  computed: {
    newIngredientsItem() {
      return this.IngredientsItem;
    },
  },
  methods: {
    addNewIgredient() {
      if (this.resetIgredient === true) {
        this.newIngredientsItem.subIgredients = [];
      }
      this.newIngredientsItem.subIgredients.push(this.newIgredient);
      this.newIgredient = "";
      this.resetIgredient = false;
      console.log("ADD: ", this.newIngredientsItem.subIgredients);
    },
    AddIngredients() {
      this.newIngredientsItem.title = this.title + this.titleNbr;
      this.titleNbr++;
      console.log("EMIT: ", this.newIngredientsItem);
      this.$emit("addIngredient", this.newIngredientsItem);
      this.resetIgredient = true;
    },
  },
};
</script>

Leave a comment