Home > Article > Web Front-end > Concept of Emit in Vue.Js
emit events.
*Determine events (event handler) *:
Using the defineEmits function, we can define the events emitted by the component.
Release events:
Events can be released using the emit function.
We will see in the detailed example below:
<template> <button @click="notifyParent">Click me</button> </template> <script setup> import { defineEmits } from 'vue' // Eventlarni aniqlash const emit = defineEmits(['myEvent']) const notifyParent = () => { emit('myEvent', 'Assalamu alaykuuuum bratanim') } </script>
<template> <div> <ChildComponent @myEvent="handleMyEvent" /> </div> </template> <script setup> import ChildComponent from './ChildComponent.vue' const handleMyEvent = (message) => { console.log(message) // Output: Assalamu alaykuuuum bratanim } </script>
<template> <button @click="sendData">Send Data</button> </template> <script setup> const emit = defineEmits(['sendData']) const sendData = () => { emit('sendData', { id: 1, name: 'Jonibek Davronov' }) } </script>
<template> <div> <ChildComponent @sendData="receiveData" /> </div> </template> <script setup> import ChildComponent from './ChildComponent.vue' const receiveData = (data) => { console.log(data) // Output: { id: 1, name: 'Jonibek Davronov' } } </script>
<template> <button @click="sendData">Send Validated Data</button> </template> <script setup> const emit = defineEmits({ // Event nomi va uni qabul qiladigan argumentlar uchun validatsiya sendData: (payload) => { if (typeof payload.id === 'number' && typeof payload.name === 'string') { return true } else { console.warn('Invalid payload') return false } } }) const sendData = () => { emit('sendData', { { id: 1, name: 'Jonibek Davronov' }) } </script>
<template> <div> <ChildComponent @sendData="handleValidatedData" /> </div> </template> <script setup> import ChildComponent from './ChildComponent.vue' const handleValidatedData = (data) => { console.log(data) // Output: { id: 1, name: 'Jonibek Davronov' } } </script>
In Vue.js, it is possible to exchange information between components using emit events. You can define events using the defineEmits function and emit events using the emit function (to the parent component). With these events, the child component can send information or report to the parent component. By validating events, we can make sure that the data sent is correct.
You can follow us on networks and if the article is useful, comment and share it with your Vuechi friends. ?
The above is the detailed content of Concept of Emit in Vue.Js. For more information, please follow other related articles on the PHP Chinese website!