[Vuejs]-VueJS2: How to update objects in an array and pass back to parent?

0👍

The first problem in Parent Component in saveFormData
if you want to check if the object exist in array or not you can use findIndex() method it loop through array and return the object index if exists else return -1 if not exist
if exist objectIndex will be greater than -1 and update that index with the object from child component and then we emit the array after updated to App.vue component

  saveFormData(x) {
      const objectIndex = this.newLocalShortNamesArr.findIndex((ele) => {
            return ele.localSnameID == x.localSnameID
      });
      
      if (objectIndex > -1) {
        // the object exists
        this.newLocalShortNamesArr[objectIndex] = { ...x };
      } else {
        // this case need new html form for add new item in array 
        this.newLocalShortNamesArr.push(x);
      }
      this.$emit("save-form-data", this.newLocalShortNamesArr);
  },

in App.vue component
we update the main array with the data that emitted from parent component

 saveFormData(x) {
      this.formValues.localShortNames = [...x];
 },

i updated the codesandbox with the new code ..
I hope the solution will be clear to you

https://codesandbox.io/s/dreamy-clarke-v04wfl?file=/src/App.vue:595-734

Leave a comment