Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

alexmamun085's avatar

Automatically mutating parent component in Vue

While changing a $data object form_data, automatically changes to paren prop!

#Blade page:

<job-listing
        :employer_question_format="{{ json_encode($employer_question_format) }}"
    ></job-listing>

#Parent compomnent:

props: [
        'employer_question_format',
    ]

#Pass to child component

<job-listing-employer-questions
                        :employer_question_formats="employer_question_format"
                    ></job-listing-employer-questions>

#Child component

<button type="button" @click="addMoreQuestion('short')" class=" ic-add-input">
                                                    <i class="ri-add-circle-line plus-icon"></i>
                                                </button>

export default {
    name: "JobListingEmployerQuestions",
    props: [
        'employer_question_formats'
    ],
    data() {
        return {
            selectedType: 'short',
            form_data: {
                employer_questions: []
            }
        }
    },
    mounted() {
        this.form_data.employer_questions = this.employer_question_formats
    },
    methods: {
        validate(){
            this.$emit('on-validate', this.$data, true)
            return true;
        },
        addMoreQuestion(type){
            let qqq = {"id":"q1","type":"short","question":"","is_required":false,"is_knockout":false,"knockout_answer":"","data_upload_by":"","user_data":""}
            this.form_data.employer_questions.push(qqq)
        }
    },
}

When I add or change anything in form_data.employer_questions , it also changes to parent component and child component prop. Please check my screenshots: By default there are 3 objects. When I add or change it also affect all over there

  1. Child component - https://prnt.sc/zPvIHefmY9EX
  2. Parent component - https://prnt.sc/qyqmacMquYuE

Why is it happening and how to do it correctly?

0 likes
1 reply
ramonrietdijk's avatar

The reason why your parent components are updated as well is because you are passing an object to the child component, binding it to your form_data. As objects are passes as references, they will be modified as well.

this.form_data.employer_questions = this.employer_question_formats

To overcome this, you may wish to clone the object given by the prop to treat it as it's own object. Using structuredClone may be helpful for this.

Please or to participate in this conversation.