Home >Web Front-end >Vue.js >How to communicate between vue components? Method introduction
Component communication
Although a child component can use this.$parent to access its parent component and any instance on its parent chain, Child components should avoid relying directly on the data of the parent component and try to explicitly use props to pass data.
In addition, it is a very bad practice to modify the state of the parent component in the child component, because:
This makes the parent component and the child component tightly coupled;
It is difficult to understand the status of the parent component only by looking at it. Because it may be modified by any subcomponent! Ideally, only the component itself can modify its state.
Each Vue instance is an event trigger:
$on() - listen for events.
$emit() - dispatches events up the scope chain. (Trigger event)
$dispatch() - Dispatch an event, which bubbles up along the parent chain.
$broadcast()——Broadcast the event and propagate the event downward to all descendants.
Monitoring and triggering
v-on listens for custom events:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <!--子组件模板--> <template id="child-template"> <input v-model="msg" /> <button v-on:click="notify">Dispatch Event</button> </template> <!--父组件模板--> <div id="events-example"> <p>Messages: {{ messages | json }}</p> <child v-on:child-msg="handleIt"></child> </div> </body> <script src="js/vue.js"></script> <script> // 注册子组件 // 将当前消息派发出去 Vue.component('child', { template: '#child-template', data: function (){ return { msg: 'hello' } }, methods: { notify: function() { if(this.msg.trim()){ this.$dispatch('child-msg',this.msg); this.msg = ''; } } } }) // 初始化父组件 // 在收到消息时将事件推入一个数组中 var parent = new Vue({ el: '#events-example', data: { messages: [] }, methods:{ 'handleIt': function(){ alert("a"); } } }) </script> </html>
The parent component can directly use v-on where the child component is used to listen to the events triggered by the child component:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <div id="counter-event-example"> <p>{{ total }}</p> <button-counter v-on:increment="incrementTotal"></button-counter> <button-counter v-on:increment="incrementTotal"></button-counter> </div> </body> <script src="js/vue.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript"> Vue.component('button-counter', { template: '<button v-on:click="increment">{{ counter }}</button>', data: function () { return { counter: 0 } }, methods: { increment: function () { this.counter += 1 this.$emit('increment') } }, }) new Vue({ el: '#counter-event-example', data: { total: 0 }, methods: { incrementTotal: function () { this.total += 1 } } }) </script> </html>
Listen to a native element on the root element of a component event. You can use .native to modify v-on. For example:
<my-component v-on:click.native="doTheThing"></my-component>
Dispatch event - $dispatch()
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <div id="app"> <p>Messages: {{ messages | json }}</p> <child-component></child-component> </div> <template id="child-component"> <input v-model="msg" /> <button v-on:click="notify">Dispatch Event</button> </template> <script src="js/vue.js"></script> <script> // 注册子组件 Vue.component('child-component', { template: '#child-component', data: function() { return { msg: '' } }, methods: { notify: function() { if (this.msg.trim()) { this.$dispatch('child-msg', this.msg) this.msg = '' } } } }) // 初始化父组件 new Vue({ el: '#app', data: { messages: [] }, events: { 'child-msg': function(msg) { this.messages.push(msg) } } }) </script> </body> </html>
The button element of the sub-component is bound to the click event. This event points to the notify method
When the notify method of the child component is processed, $dispatch is called, the event is dispatched to the child-msg event of the parent component, and the event is provided with A msg parameter
The child-msg event is defined in the events option of the parent component. After the parent component receives the dispatch of the child component, it calls the child-msg event.
Broadcast event - $broadcast()
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <div id="app"> <input v-model="msg" /> <button v-on:click="notify">Broadcast Event</button> <child-component></child-component> </div> <template id="child-component"> <ul> <li v-for="item in messages"> 父组件录入了信息:{{ item }} </li> </ul> </template> <script src="js/vue.js"></script> <script> // 注册子组件 Vue.component('child-component', { template: '#child-component', data: function() { return { messages: [] } }, events: { 'parent-msg': function(msg) { this.messages.push(msg) } } }) // 初始化父组件 new Vue({ el: '#app', data: { msg: '' }, methods: { notify: function() { if (this.msg.trim()) { this.$broadcast('parent-msg', this.msg) } } } }) </script> </body> </html>
The opposite of dispatching events. The former is bound in the child component and calls $dispatch to dispatch to the parent component; the latter is bound in the parent component and calls $broadcast to broadcast to the child component.
Access between parent and child components
Parent component accesses child components: use $children or $refs
Child components access parent components: use $parent
Child components access root components: use $root
$children:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <div id="app"> <parent-component></parent-component> </div> <template id="parent-component"> <child-component1></child-component1> <child-component2></child-component2> <button v-on:click="showChildComponentData">显示子组件的数据</button> </template> <template id="child-component1"> <h2>This is child component 1</h2> </template> <template id="child-component2"> <h2>This is child component 2</h2> </template> <script src="js/vue.js"></script> <script> Vue.component('parent-component', { template: '#parent-component', components: { 'child-component1': { template: '#child-component1', data: function() { return { msg: 'child component 111111' } } }, 'child-component2': { template: '#child-component2', data: function() { return { msg: 'child component 222222' } } } }, methods: { showChildComponentData: function() { for (var i = 0; i < this.$children.length; i++) { alert(this.$children[i].msg) } } } }) new Vue({ el: '#app' }) </script> </body> </html>
$ref can specify the index ID for child components:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <div id="app"> <parent-component></parent-component> </div> <template id="parent-component"> <!--<child-component1></child-component1> <child-component2></child-component2>--> <child-component1 v-ref:cc1></child-component1> <child-component2 v-ref:cc2></child-component2> <button v-on:click="showChildComponentData">显示子组件的数据</button> </template> <template id="child-component1"> <h2>This is child component 1</h2> </template> <template id="child-component2"> <h2>This is child component 2</h2> </template> <script src="js/vue.js"></script> <script> Vue.component('parent-component', { template: '#parent-component', components: { 'child-component1': { template: '#child-component1', data: function() { return { msg: 'child component 111111' } } }, 'child-component2': { template: '#child-component2', data: function() { return { msg: 'child component 222222' } } } }, methods: { showChildComponentData: function() { // for (var i = 0; i < this.$children.length; i++) { // alert(this.$children[i].msg) // } alert(this.$refs.cc1.msg); alert(this.$refs.cc2.msg); } } }) new Vue({ el: '#app' }) </script> </body> </html>
The effect is the same as $children.
$parent:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <div id="app"> <parent-component></parent-component> </div> <template id="parent-component"> <child-component></child-component> </template> <template id="child-component"> <h2>This is a child component</h2> <button v-on:click="showParentComponentData">显示父组件的数据</button> </template> <script src="js/vue.js"></script> <script> Vue.component('parent-component', { template: '#parent-component', components: { 'child-component': { template: '#child-component', methods: { showParentComponentData: function() { alert(this.$parent.msg) } } } }, data: function() { return { msg: 'parent component message' } } }) new Vue({ el: '#app' }) </script> </body> </html>
As mentioned at the beginning, it is not recommended to modify the state of the parent component in the child component.
Non-parent-child component communication
Sometimes components with non-parent-child relationships also need to communicate. In a simple scenario, use an empty Vue instance as the central event bus:
var bus = new Vue() // 触发组件 A 中的事件 bus.$emit('id-selected', 1) // 在组件 B 创建的钩子中监听事件 bus.$on('id-selected', function (id) { // ... })
Related recommendations:
2020 Summary of front-end vue interview questions (With answers)
vue tutorial recommendation: The latest 5 vue.js video tutorial selections in 2020
More programming-related knowledge, Please visit: Introduction to Programming! !
The above is the detailed content of How to communicate between vue components? Method introduction. For more information, please follow other related articles on the PHP Chinese website!