0
votes

I am trying to pass an object as a prop from a parent component and then initialize the child with the value.

The purpose of this is to open a dialog which contains a child component that is a form with several pages. After one of the pages is filled out, the changes are sent to the parent and the next page of the dialog comes up. If the user wants to navigate to the previous dialog screen, then it will need to be initialized with the values from the parent that were updated.

  /* PARENT */
  <template>
    <CompanyInfo :editedClient="editedClient" />
  </template>
  <script>
    import CompanyInfo from './CompanyInfo.vue'
    export default {
      name: 'Client',
      components: {
        'CompanyInfo': CompanyInfo
      },
      data: () => ({
        editedClient: {
          name: 'aaaa',
          website: '',
          locations: [],
          contacts: [
              {
                  firstName: '',
                  lastName: '',
                  emails: [{ email: '' }],
                  phoneNumbers: [{ phoneNumber: ''}],
                  notes: []
              }
          ]
        },
      })
    }
  </script>


 /* CHILD */
 <template></template>
 <script>
   export default {
     name: 'CompanyInfo',
     data: () => {
       props: [ 'editedClient' ],
       companyInfo: {
         name: this.editedClient.name, //this throws an error when directly initialized like this
         website: this.editedClient.email, //the error says that 'this' is undefined
         locations: this.editedClient.locations //tried initializing this with mounted() hook
       }
     },
     beforeCreate() {
       console.log(this.editedClient.name) // this prints undefined to the console
     }
   }
 </script>
1
what does not work?HW Siew
Props should be outside of your data function in the child component. Also if you use an arrow function with the data property, this won’t be the component’s instance.Andrew1325
@Andrew1325 This worked great and was what I ended up using.insite

1 Answers

0
votes

You can use the computed property in vue for this. And props is recieved outside the data property

/* CHILD */
 <template></template>
 <script>
   export default {
     name: 'CompanyInfo',
     props: {
       editedClient: {
         type: Object,
         default: () => {
          name: '',
          website: '',
          locations: ''
         }
       }
     },
     computed: {
       companyInfo: {
         get() {
           return {
             name: this.editedClient.name,
             website: this.editedClient.email,
             locations: this.editedClient.locations
           }
         }
       }
     },
     data: () => {
           },
     mounted() {
       console.log(this.companyInfo.name)
     }
   }
 </script>