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

半城伤御伤魂 提交于 2021-01-23 05:37:26

问题


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:

  • Use $broadcast to propagate an event e1 downwards from the submit handler
  • Listen for the e1 event in UserAddress
  • Use $dispatch to send an event e2 and bundle the address data with the message
  • Listen for e2 in UserData, add the other form data to the message, and propagate or re-dispatch the event
  • Listen for e2 in UserPage and find the full aggregated data there.

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.


回答1:


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



来源:https://stackoverflow.com/questions/36499665/how-to-access-data-from-deeply-nested-child-components-in-vue-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!