Implementation of mutual communication between parent and child components in Vue2.x, vue2.x Parent and Child
Business scenario: (this refers to direct parent-child relationship Communication)
- Beauty (child component) sends messages to a large group (parent component)
- A large group (parent component) receives a message from a beauty and returns a message to the beauty (child component)
Parent component
Template
<Template> <div> <p> group message girl: </p> <div >{{ somebody }}said: I am {age. </Div>
Note:
- Here, the parent component uses v-on to listen to custom events on the child component ($ emit changes). Once the noticeGirl method changes, it will trigger
<Script> import vGirlGroup from '. /GirlGroup 'export default {name: 'girl ', components: {vGirlGroup}, data () {return {aGirls: [{name: 'lily', age: 22 }, {name: 'xiaomei ', age: 21}, {name: 'xiaohe', age: 24}], somebody: '', age:'', noticeGirl: ''}}, methods: {introduceSelf (opt) {this. somebody = opt. name; this. age = opt. age; // notify girl to receive the message this. noticeGirl = opt. name + ', message received' ;}}</script>
Note:
The method defined in methods, introduceSelf, is the $ emit event handler that the parent component receives from the child component.
Child Widgets
Template
<Template> <div> <ul> <li v-for = "(value, index) in girls" >{{ index }}-{ value. name }}-{ {value. age }}< button @ click = "noticeGroup (value. name, value. age) "> send messages </button> </li> </ul> <div> receive messages from large groups: {noticeGirl }}</div> </template>
Script
<script>export default { name: 'girl-group', props: { girls: { type: Array, required: true }, noticeGirl: { type: String, required: false } }, methods: { noticeGroup (name, age) { this.$emit('introduce',{ name: name, age: age }) } }}</script>
Note:
Child components use $ emit to send custom events
Compared with Vue1.x:
$ Dispatch and $ broadcast have been deprecated
* Officially recommended communication methods
Vuex preferred
Use event Bus: eventBus, allowing components to communicate freely
For details, see https://cn.vuejs.org/v2/guide/migration.html?dispatch-and -broadcast-replace.
Result
The above section describes how the parent and child components in Vue2.x communicate with each other and hope to help you. If you have any questions, please leave a message and the editor will reply to you in time. Thank you very much for your support for the help House website!