SoFunction
Updated on 2025-04-11

How to use Vue3 emits combined with callback function

Vue3 emits combined with callback function

Callback function

Let’s talk about what a callback function is, for example:

When method A calls method B, method A will pass a method as a parameter to method B. Method B can execute the functions passed by A according to logic, which is to call the method A passed parameter to.

It's a bit confusing, please refer to the following code:

const funA = () => {
	// Business logic ......	
	funB('Brabra', 123, () => {
		// Business logic of callbacks	});
};


/**
 * Method B It is best to add ts constraints
 * @param param1 Param1
 * @param param2 Param2
 * @param fun1 Parameter function 1, here is a function
 */
const funB = (param1:string, param2: number, fun1: Function){
	// Get the parameters to do business...
	// Execute the parameter function, here the method passed into method A will be executed	fun1();
}

There are actually many examples of this in vue:

For example, many of the logical processing of vue responsiveness are to store functions in map set sets and then do logic. The main idea here is that method parameters can not only pass ordinary parameters, but also functions, and set storage can also store functions to wait for special types.

emits callback function

Going back to the topic, it will be easy to understand here in combination with the above code.

Normal emits is used for communication between child and parent components. The child components communicate with the parent components. Using the callback function is to ask the parent component to accept the message from the child component and then call back to the child component.

// Subcomponentsemtis('demoBack', data, () => {
	// Callback business});


// Parent component<Subcomponents @demoBack="handleDemoBack">

const handleDemoBack = (data, fun) => {
	// data is the data passed
	// Execute callback function	fun();
};

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.