Vuejs : How to pass an object as prop and have the component update sub-objects

前端 未结 5 1315
小鲜肉
小鲜肉 2021-01-02 23:16

I am trying to create a component that accepts an object as prop and can modify different properties of that object and return the value to the parent, using either sync or

5条回答
  •  情书的邮戳
    2021-01-02 23:37

    You shouldn't modify the object being passed in as a prop. Instead, you should create a new data property in the child component and initialize it with a copy of the prop object.

    Then, I would just use a v-model for each of the inputs in the child component and add a deep watcher to the internal value which would emit an update whenever the internal value changes.

    Vue.component('child', {
      template: '#child',
      props: ['value'],
      data() {
        return { val: {...this.value} };
      },
      watch: {
        val: {
          deep: true,
          handler(value) {
            this.$emit('input', value);
          }
        }
      }
    });
    
    new Vue({
      el: '#app',
      data: {
        parentObject: {value1: "1st Value", value2: "2nd value"}
      }
    });
    
    
    

    Parent value: {{parentObject}}

    I made a shallow copy of the prop in my example ({...this.value}), because the object doesn't have any nested properties. If that wasn't the case, you might need to do a deep copy (JSON.parse(JSON.stringify(this.value))).

提交回复
热议问题