【问题标题】:Automatically mutating parent component in Vue在 Vue 中自动改变父组件
【发布时间】:2022-09-17 00:48:57
【问题描述】:

在更改 $data 对象表单数据时,会自动更改为父道具!

#刀片页面:

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

#父组件:

props: [
        \'employer_question_format\',
    ]

#传递给子组件

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

#子组件

<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)
        }
    },
}

当我在 form_data.employer_questions 添加或更改任何内容时,它也会更改为父组件和子组件道具。请检查我的截图: 默认情况下有 3 个对象。当我添加或更改时,它也会影响那里

  1. 子组件 - https://prnt.sc/zPvIHefmY9EX
  2. 父组件 - https://prnt.sc/qyqmacMquYuE

    为什么会发生以及如何正确地做到这一点?

    标签: laravel vue.js vuejs2 vue-component


    【解决方案1】:

    当您将一个数组分配给另一个数组时,您将传递第一个数组的参考值,这意味着对一个数组的更改将影响另一个。为了防止这种情况,您可以在分配期间创建数组的浅表副本。有多种方法可以做到这一点:

    spread syntax (ES6)

    this.form_data.employer_questions = [...this.employer_question_formats]
    

    Array.from()

    this.form_data.employer_questions = Array.from(this.employer_question_formats)
    

    Array.prototype.slice()

    this.form_data.employer_questions = this.employer_question_formats.slice()
    

    【讨论】:

      猜你喜欢
      • 2021-06-16
      • 2021-03-08
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      • 2017-07-10
      • 2021-07-23
      相关资源
      最近更新 更多