问题
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
$broadcastto propagate an evente1downwards from the submit handler - Listen for the
e1event inUserAddress - Use
$dispatchto send an evente2and bundle the address data with the message - Listen for
e2inUserData, add the other form data to the message, and propagate or re-dispatch the event - Listen for
e2inUserPageand 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