0

我正在尝试将对象作为来自父组件的道具传递,然后使用该值初始化子组件。

这样做的目的是打开一个对话框,其中包含一个子组件,该组件是一个具有多个页面的表单。填写完其中一个页面后,更改将发送给父级,并出现对话框的下一页。如果用户想要导航到上一个对话框屏幕,则需要使用父级更新的值对其进行初始化。

  /* 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>
4

1 回答 1

0

您可以为此使用 vue 中的计算属性。并且在 data 属性之外收到了 props

/* 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>
于 2020-06-19T07:15:18.510 回答