amoe
amoe

Reputation: 4569

How to access data from deeply nested child components in Vue.js

I am building an interface using Vue.js. I have a form, this form contains an address, and other bits of miscellaneous data. So I created two components in Vue, UserData and UserAddress. UserData contains an instance of UserAddress as a child component. I want to specialize the behaviour of the "Submit" button for the form depending on the page, so these components don't contain the submit button -- the outer component, representing the page (UserPage) contains the submit button, and just includes the UserData template.

So the hierarchy goes, UserPage => UserData => UserAddress.

Now I need to get ALL the form data within some method on UserPage. I would just say that I need to get it within the submit handler, but the only way that I can think to do this without directly accessing the data of the child components is the following:

Is this a normal method for dealing with a situation like this? It seems like overkill, but accessing child $data is explicitly non-recommended by the manual.

Upvotes: 4

Views: 2115

Answers (1)

Yerko Palma
Yerko Palma

Reputation: 12329

Use twoWay props. If you declare twoWay: true in a child property, and pass a variable from the parent like :child-prop.sync="parent-data", then the value of the property is written on the parent. You can make a chain with this. The code would be like this

child

<template>
  <input v-model="address">
</template>
<script>
export default {
  props: {
    address: {
      type: String,
      twoWay: true
    }
  }
}
</script>

parent

<template>
  <div>
    <input v-model="uname">
    <user-address :address.sync="uaddress"></user-address>
  </div>
</template>
<script>
export default () {
  components: {
    'user-address': userAddress
  },
  props: {
    uaddress: {
        type: String,
      twoWay: true
    },
    uname: {
        type: String,
      twoWay: true
    }
  }
}
</script>

check this fiddle with the chain userPage => userData => userAddress

Upvotes: 4

Related Questions