Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use $emit in vue

Shulou Source: shulou.com Published: 2022-06-01 05:14:27 10月04日 Update

This article mainly shows you "how to use $emit in vue". The content is simple and clear. I hope it can help you solve your doubts. Let the editor lead you to study and learn this article "how to use $emit in vue".

In vue, "$emit" is used to trigger events on the current instance, and nearby parameters are passed to the listener for callback; child components can use "$emit" to trigger custom events of the parent component with the syntax of "vm.$emit (event, [… args])".

This article operating environment: windows10 system, Vue2.9.6 version, DELL G3 computer.

The usage of $emit in vue

Events are triggered using $emit (eventName) in vue

$emit (eventName) triggers the event on the current instance, and the additional parameters are passed to the listener callback.

Trigger an event using $emit (eventName)

The explanation in Api:

Vm.$emit (event, [… Args])

About the usage of $emit in vue

1. The parent component can use props to transfer data to the child component.

2. A child component can use $emit to trigger a custom event for the parent component.

Vm.$emit (event, arg) / / triggers the event vm.$on (event, fn) on the current instance; / / runs fn after listening for the event event

Examples are as follows:

Sub-component

ToCity passed by parent component to child component: {{sendData}} Click here to transmit 'Dalian' to parent component export default {name:'trainCity', props: ['sendData'], / / to receive data passed by parent component to child component methods: {select (val) {let data = {cityname: val} After the this.$emit ('showCityName',data); / / select event is triggered, the showCityName event} is automatically triggered.

Parent component:

ToCity {{toCity}} import TrainCity from ". / train-city" of the parent component Export default {name:'index', components: {TrainCity}, data () {return {toCity: "Beijing"}}, methods: {updateCity (data) {/ / trigger sub-component city selection-event this.toCity = data.cityname / / changed the value of the parent component console.log ('toCity:'+this.toCity)} above is all the content of the article "how to use $emit in vue". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Tags: Components events content instances articles monitoring parameters cities data listeners learning help selection understandability more organization environment computers knowledge examples Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Apple Redmi vpn Docker NVidia