Vue parent component click to trigger sub-component event instance description, vue instance description
I recently learned about the communication between Vue parent and child components. I just encountered an event dispatching and receiving between parent and child. Here I will record it. Here I am using ref
Register the reference information for the sub-component.Official WebsiteYes.
Ref is used to register reference information for an element or child component. The reference information is registered on the $ refs object of the parent component. If it is used on a common DOM element, the reference points to the DOM element. If it is used on a child component, the reference points to the component instance:
Parent component app. vue
<Template> <div id = "app"> <! -- Parent component --> <input v-model = "msg"> <button v-on: click = "Y"> broadcast events </button> <! -- Sub-component --> <popup ref = "child"> </popup> </div> </template> <script> import popup from '@/components/popup' export default {name: 'app', data: function () {return {msg: ''}, components: {popup}, methods: {role Y: function () {if (this. msg. trim () {this. $ refs. child. parentMsg (this. msg) }}</script> <style> # app {font-family: 'Avenir ', Helvetica, Arial, sans-serif;-webkit-font-smoothing: antialiased;-moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px ;}</style>
Sub-component popup. vue
<Template> <div> <ul> <li v-for = "item in messages"> the parent component inputs: {item }}</li> </ul> </div> </template> <style> body {background-color: # ffffff ;} </style> <script> export default {name: 'popup', data: function () {return {messages: []}, methods: {parentMsg: function (msg) {this. messages. push (msg) }}</script>
I will explain this instance in several steps:
1. The button element of the parent component is bound to the click event, which points to the Y method.
2. Register a ref = "child" for the sub-component"
3. during processing, the notify method of the parent component uses $ refs. child to pass the event to the parentMsg method of the child component, and carries the parameter msg of the parent component.
4. After the child component receives the event of the parent component, it calls the parentMsg method and places the received msg in the message array.
The running result is as follows:
The example of the above vue parent component clicking to trigger the sub-component event is all the content shared by Alibaba Cloud. I hope to give you a reference and support for the customer's home.