Table of Contents
Schematic diagram
Communication between components through props
Communication between components is realized through the component’s custom event
Other knowledge points about component custom events
{{msg}}
Unbinding of custom event
籍贯:{{native}}
详细地址:{{adress}}
总结
Home Web Front-end Vue.js Deep dive into custom events in Vue components

Deep dive into custom events in Vue components

Apr 06, 2022 pm 08:12 PM
vue components Custom events

What are component custom events? This article will give you an in-depth understanding of the custom events in the Vue component, and talk about the points to note about custom events. I hope it will be helpful to you!

Deep dive into custom events in Vue components

The custom event of a component is a communication method between components. It is suitable for child components to transmit data or behavior to parent components. (Learning video sharing: vuejs tutorial)

Schematic diagram

Deep dive into custom events in Vue components

Notes on custom events of components:

  • 1. The custom event of the component implements the function of communication between the child component and the parent component. Therefore, the binding action of the custom event needs to be completed in the parent component

  • 2. The triggering action of the component's custom event needs to be completed in the sub-component. Whoever binds the event will be triggered

Before understanding the custom events of components, we also learned about props. props can also realize child components to communicate with parent components. Next, I will start with props way to transition to the component's custom events, so that everyone can better understand the component's custom events, and you can also compare the differences and similarities between the two methods

Communication between components through props

In App.vue:

<!-- 通过父组件给子组件传递函数类型的props实现:子给父传递数据 -->
<TestA :getName="getName"/>
...
...
<script>
import TestA from &#39;./components/TestA&#39;
	export default {
		name:&#39;App&#39;,
		components:{TestA},
		data(){
			return{
				msg:&#39;你好呀&#39;
			}
		},
		methods:{
			getName(name){
				console.log(&#39;App组件收到了数据&#39;, name)
			},
		},
	}
</script>
Copy after login

In the code snippetgetName()In the method name parameter is used to receive the parameters passed by the sub-component

TestA.vue:

<!--通过点击事件传递数据-->
<button @click="sendName">将姓名发送给App组件</button>
...
...
<script>
export default {
    name:&#39;TestA&#39;,
    //接收父组件传递过来的props
    props:["getName"],
    data(){
        return{
            name:&#39;路飞&#39;,
            age:18
        }
    },
    methods:{
        sendName(){
            //点击按钮后,触发此方法,传递name给父组件
            this.getName(this.name)
        }
    }
}
</script>
Copy after login

The above is the sub-component using props to send the message to the parent Component transfer data

The effect diagram is as follows:

Page initialization effect:

Deep dive into custom events in Vue components

After clicking the button:

Deep dive into custom events in Vue components

As can be seen from the picture, when the button is clicked, the console outputs the data received by the parent component, and the child component sends the data to the parent through props The component passed the data

Communication between components is realized through the component’s custom event

The first step is to bind a custom event to the component. The article begins That is to say, binding custom events is completed in the parent component:

Deep dive into custom events in Vue components

#Secondly, in the child component, the custom event needs to be triggered to complete the component customization Event communication:

Deep dive into custom events in Vue components

The effect diagram is as follows:

Page initialization effect:

Deep dive into custom events in Vue components

After clicking the button:

Deep dive into custom events in Vue components

As can be seen from the picture, when the button is clicked, the console outputs the data received by the parent component.

Through the above two communication methods, we can find that the child component passes data to the parent component through props. The premise is that the parent component must pass a callback function to the child component, only after the child component receives it can it pass data to the parent component, and the component's custom event only needs to call the $emit method to trigger the specified custom event , and then it can be sent to the parent component. The parent component passes data.

Other knowledge points about component custom events

The second way to customize component binding

App.vue:

<template>
	<div class="app">
		<h1 id="msg">{{msg}}</h1>
		<!-- 通过父组件给子组件传递函数类型的props实现:子给父传递数据 -->
		<TestA :getName="getName"/>
		<!-- 通过父组件给子组件绑定一个自定义事件实现:子给父传递数据 -->
    <!--方法二-->
		<TestB ref="testb"/>
	</div>
</template>

<script>
import TestA from &#39;./components/TestA&#39;
import TestB from &#39;./components/TestB&#39;
	export default {
		name:&#39;App&#39;,
		components:{TestA, TestB},
		data(){
			return{
				msg:&#39;你好呀&#39;
			}
		},
		methods:{
			getName(name){
				console.log(&#39;我收到了数据&#39;, name)
			},
			send(name){
				console.log("send被调用了", name)
			}
		},
		mounted(){
			this.$refs.testb.$on(&#39;demo&#39;, this.send);
		}
	}
</script>

<style scoped>
.app{
	background-color: rgb(162, 255, 139);
	padding: 15px;
}
</style>
Copy after login

Get the instance object (vc)

of the TestB component through the ref attribute, after the component is mounted (mounted) Use this.$refs.component name.$on('custom event name', callback function) to complete the binding of the sub-component custom event, and the same effect can be achieved.

Moreover, using this method is more flexible and can complete some operations, such as one-time custom events, delay, judgment, etc.

One-time custom event

v-on:事件名.once="XXXX
或者
this.$refs.student.$once("事件名", 事件内容)
Copy after login

Unbinding of custom event

When we have finished using the custom event , you can unbind custom events. The advantage of doing this is to minimize the occupation of program performance and improve the efficiency of program operation.

The custom unbinding action is also performed in sub-components,

Simple In other words, whoever bound it can unbind it

TestB

<template>
  <div>
      <h2 id="籍贯-native">籍贯:{{native}}</h2>
      <h2 id="详细地址-adress">详细地址:{{adress}}</h2>
      <button @click="sendNative">点击触发自定义事件</button>
      <button @click="noBand">解绑自定义事件</button>
  </div>
</template>

<script>
export default {
    name:&#39;TestB&#39;,
    data(){
        return{
            native:&#39;东海&#39;,
            adress:&#39;东海风车村&#39;
        }
    },
    methods:{
        sendNative(){
            this.$emit(&#39;demo&#39;,this.native)
        },
        //解绑demo自定义事件
        noBand(){
            this.$off(&#39;demo&#39;);
        }
    }
    
}
</script>

<style scoped>
div{
    background-color: aquamarine;
    padding: 15px;
    margin-top: 5px;
}
</style>
Copy after login

Another point is that if there are many customizations If the event needs to be unbound, you can write it like this:

{方法体内
    this.$off();
}
Copy after login

直接不用传递任何参数,这样写的话,只要是给此组件绑定的任何自定义事件都会解绑

总结

以上内容就是组件的自定义事件的使用,自定义事件虽然在Vuejs中不是一个非常重要的点,但是也是一个实际开发中比较常用的点,在进行某些业务操作时,使用自定义事件可能会节省开发时间以及优化代码,减少代码冗余量,组件自定义事件的具体操作还要看所处的业务逻辑和行为是什么。

Deep dive into custom events in Vue components

如果觉得内容不错的话,记得点赞收藏~~~

(学习视频分享:web前端开发

The above is the detailed content of Deep dive into custom events in Vue components. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

How to add functions to buttons for vue How to add functions to buttons for vue Apr 08, 2025 am 08:51 AM

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

How to use watch in vue How to use watch in vue Apr 07, 2025 pm 11:36 PM

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

What does vue multi-page development mean? What does vue multi-page development mean? Apr 07, 2025 pm 11:57 PM

Vue multi-page development is a way to build applications using the Vue.js framework, where the application is divided into separate pages: Code Maintenance: Splitting the application into multiple pages can make the code easier to manage and maintain. Modularity: Each page can be used as a separate module for easy reuse and replacement. Simple routing: Navigation between pages can be managed through simple routing configuration. SEO Optimization: Each page has its own URL, which helps SEO.

How to reference js file with vue.js How to reference js file with vue.js Apr 07, 2025 pm 11:27 PM

There are three ways to refer to JS files in Vue.js: directly specify the path using the &lt;script&gt; tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

How to return to previous page by vue How to return to previous page by vue Apr 07, 2025 pm 11:30 PM

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses &lt;router-link to=&quot;/&quot; component window.history.back(), and the method selection depends on the scene.

How to use vue traversal How to use vue traversal Apr 07, 2025 pm 11:48 PM

There are three common methods for Vue.js to traverse arrays and objects: the v-for directive is used to traverse each element and render templates; the v-bind directive can be used with v-for to dynamically set attribute values ​​for each element; and the .map method can convert array elements into new arrays.

How to jump to the div of vue How to jump to the div of vue Apr 08, 2025 am 09:18 AM

There are two ways to jump div elements in Vue: use Vue Router and add router-link component. Add the @click event listener and call this.$router.push() method to jump.

See all articles