


How to operate $emit and $on in vue to communicate with parent-child and sibling components
This time I will show you how to operate $emit and $on parent-child and sibling components in vue to communicate, and how to operate $emit and $on parent-child and sibling components in vue. What are the precautions, below This is a practical case, let’s take a look at it.
There are three main transmission methods:
1. Communication from parent component to child component
2. Communication from child component to parent component
3. Communication between sibling components
1. Parent component passes value to child component
Parent component passes values to child component using props
//父组件:parent.vue <template> <p> <child :vals = "msg"></child> </p> </template> <script> import child from "./child"; export default { data(){ return { msg:"我是父组件的数据,将传给子组件" } }, components:{ child } } </script> //子组件:child.vue <template> <p> {{vals}} </p> </template> <script> export default { props:{ //父组件传值 可以是一个数组,对象 vals:{ type:String,//类型为字符窜 default:"123" //可以设置默认值 } }, } </script>
2. Communication from child component to parent component
Use $emit(eventname,option)
Trigger event,
Parameter 1: Customize the event name, written in lowercase or connected with -, such as event, event-name cannot be written in camel case (eventName)
The sub-component passes the value to the parent component and can be used in the sub-component The value of the event triggered by $emit is passed out, and the parent component obtains the data through event monitoring.
However, there is a problem here.
1. It is the child component that actively transmits data to the parent component. The parent component listens and receives (it is determined by the operation in the child component when to pass the value)
2. Or it is the parent component that determines when the child component passes the value to the parent component, and then listens and receives (it is determined by the operation in the parent component) When to pass the value)
Both cases exist
2.1: $meit event trigger, customized through event trigger inside sub-component Event $emit
2.2: The $meit event is triggered. The custom event $emit
can be triggered by the event of the parent component operating the child component (ref). The first case:
//父组件:parent.vue <template> <p> <child v-on:childevent='wathChildEvent'></child> <p>子组件的数据为:{{msg}}</p> </p> </template> <script> import child from "./child"; export default { data(){ return{ msg:"" } }, components:{ child }, methods:{ wathChildEvent:function(vals){//直接监听 又子组件触发的事件,参数为子组件的传来的数据 console.log(vals);//结果:这是子组件的数据,将有子组件操作触发传给父组件 this.msg = vlas; } } } </script> //子组件:child.vue <template> <p> <input type="button" value="子组件触发" @click="target"> </p> </template> <script> export default { data(){ return { texts:'这是子组件的数据,将有子组件操作触发传给父组件' } }, methods:{ target:function(){ //有子组件的事件触发 自定义事件childevent this.$emit('childevent',this.texts);//触发一个在子组件中声明的事件 childEvnet } }, } </script>
Second case:
//父组件:parent.vue <template> <p> <child v-on:childevent='wathChildEvent' ref="childcomp"></child> <input type="button" @click="parentEnvet" value="父组件触发" /> <p>子组件的数据为:{{msg}}</p> </p> </template> <script> import child from "./child"; export default { data(){ return{ msg:"" } }, components:{ child }, methods:{ wathChildEvent:function(vals){//直接监听 又子组件触发的事件,参数为子组件的传来的数据 console.log(vals);//这是子组件的数据,将有子组件操作触发传给父组件 this.msg = vlas; }, parentEnvet:function(){ this.$refs['childcomp'].target(); //通过refs属性获取子组件实例,又父组件操作子组件的方法触发事件$meit } } } </script> //子组件:child.vue <template> <p> <!-- dothing..... --> </p> </template> <script> export default { data(){ return { texts:'这是子组件的数据,将有子组件操作触发传给父组件' } }, methods:{ target:function(){ //又子组件的事件触发 自定义事件childevent this.$emit('childevent',this.texts);//触发一个在子组件中声明的事件 childEvnet } }, } </script>
Comparing the two situations, the difference lies in whether the $emit custom event is triggered by a parent component or a child component To trigger
The first way is to define a click event in the child component to trigger the custom event $emit, and then listen to it in the parent component
The second way is to use it in the parent component For the first click event, obtain the instance method through refs in the component to directly trigger the event, and then listen in the parent component
3. Communication between sibling components
(1) , Transfer data between brothers through events
(2) Create a new Vue instance so that each brother shares the same event mechanism. (Key points)
(3) When passing data, $emit (method name, passed data) is triggered through events.
(4) The data receiving party triggers the event $on (method name, callback (received data)) in the mounted() hook function (mounted instance). At this time, this in the callback function Changes have been made to use arrow functions.
//建立一个空的Vue实例,将通信事件挂载在该实例上 //emptyVue.js import Vue from 'vue' export default new Vue() //兄弟组件a:childa.vue <template> <p> <span>A组件->{{msg}}</span> <input type="button" value="把a组件数据传给b" @click ="send"> </p> </template> <script> import vmson from "./emptyVue" export default { data(){ return { msg:"我是a组件的数据" } }, methods:{ send:function(){ vmson.$emit("aevent",this.msg) } } } </script> //兄弟组件b:childb.vue <template> <p> <span>b组件,a传的的数据为->{{msg}}</span> </p> </template> <script> import vmson from "./emptyVue" export default { data(){ return { msg:"" } }, mounted(){ vmson.$on("aevent",(val)=>{//监听事件aevent,回调函数要使用箭头函数; console.log(val);//打印结果:我是a组件的数据 this.msg = val; }) } } </script> //父组件:parent.vue <template> <p> <childa><childa> <childb></childb> </p> </template> <script> import childa from "./childa"; import childb from "./childb"; export default { data(){ return{ msg:"" } }, components:{ childa, childb }, } </script>
At this point, the component communication and value transfer in Vue can basically be solved, but for large and complex projects, it is recommended to use vuex state management to be more suitable....
I believe I have read this article You have mastered the case method. For more exciting information, please pay attention to other related articles on the PHP Chinese website!
Recommended reading:
How to optimize js async function
The above is the detailed content of How to operate $emit and $on in vue to communicate with parent-child and sibling components. For more information, please follow other related articles on the PHP Chinese website!

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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.
