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 ></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 id="This-nbsp-is-nbsp-child-nbsp-component-nbsp">This is child component 1</h2> </template> <template id="child-component2"> <h2 id="This-nbsp-is-nbsp-child-nbsp-component-nbsp">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 id="This-nbsp-is-nbsp-child-nbsp-component-nbsp">This is child component 1</h2> </template> <template id="child-component2"> <h2 id="This-nbsp-is-nbsp-child-nbsp-component-nbsp">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 id="This-nbsp-is-nbsp-a-nbsp-child-nbsp-component">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!

本篇文章带大家聊聊vue指令中的修饰符,对比一下vue中的指令修饰符和dom事件中的event对象,介绍一下常用的事件修饰符,希望对大家有所帮助!

react与vue的虚拟dom没有区别;react和vue的虚拟dom都是用js对象来模拟真实DOM,用虚拟DOM的diff来最小化更新真实DOM,可以减小不必要的性能损耗,按颗粒度分为不同的类型比较同层级dom节点,进行增、删、移的操作。

在VSCode中开发Vue/React组件时,怎么实时预览组件?本篇文章就给大家分享一个VSCode 中实时预览Vue/React组件的插件,希望对大家有所帮助!

Vue组件通信:使用回调函数进行组件通信在Vue应用程序中,有时候我们需要让不同的组件之间进行通信,以便它们可以共享信息和相互协作。Vue提供了多种方式来实现组件之间的通信,其中一种常用的方式是使用回调函数。回调函数是一种将一个函数作为参数传递给另一个函数并在特定事件发生时被调用的机制。在Vue中,我们可以利用回调函数来实现组件之间的通信,使得一个组件可以在

本篇文章给大家分享一个Vue+Laravel开发教程,介绍一下怎么使用 Vue.js 和 Laravel 共建一个简单的 CRUD 应用,希望对大家有所帮助!

svg图片在项目中使用的非常广泛,下面本篇文章带大家介绍一下如何在vue3 + vite 中使用svg图标,希望对大家有所帮助!


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.