Home > Software engineering >  $emit object to parent component, and push to array. Objects in array continue to be reactive, why?
$emit object to parent component, and push to array. Objects in array continue to be reactive, why?

Time:12-10

I'm trying to make a function where users can added multiple resume posts (from child component) to an array (in parent). The problem is, every object I push to parent array stays reactive with the child form/object. So if I for example clear the form in child component, the Object I pushed to the parent array gets all it's values cleared as well. How to I emit and push the post-object to parent array and stop it from being reactive, so I can add new/more resume posts?

CreateProfile.vue

<template>
    <ResumePostInput :resume_posts="form.resume_posts" @resumeHandler="handleResume"/>
</template>

<script>
export default {
    data() {
         form: {
              resume_posts: []
         }
    }
    methods: {
        handleResume(post) {
            this.form.resume_posts.push(post)
        }
    }
}
</script>

ResumePostInput.vue

<template
-- Input fields binded to post object --
</template>

<script>  
export default {
    emits: ["resumeHandler"],
    props: {
         resume_posts: Array
    },
    data() {
        return {
            post: {
                title: '',
                sub_title: '',
                text: '',
                year_from: '',
                year_to: '',
                type: ''
            }
        }
    },
    methods: {
        addResume() {
            this.$emit("resumeHandler", this.post)
        }
    }
}
</script>

CodePudding user response:

you emit unknown property, it's a post, not posts

and learn about JS object, there are copy by reference & value

maybe you just need to update your addResume method like this

   addResume() {
      const post = JSON.parse(JSON.stringify(this.post))
      this.$emit("resumeHandler", post)
   }

CodePudding user response:

It's not the problem that the object is reactive but that it's the same object because objects are passed by reference in JavaScript. If it's modified in one place, it's modified everywhere.

In order to avoid this, the object needs to be explicitly copied. For shallow object this can be done with object spread:

this.$emit("resumeHandler", {...this.post})

For deeply nested objects, multiple spreads or third-party clone function can be used.

  • Related