Home > Article > Web Front-end > What is the usage of emit in vue
In vue, emit is used by sub-components to call methods of parent components and pass data; sub-components can use "$emit" to trigger custom events of parent components. After the event is triggered, additional parameters will be passed to the listener. Callback, the syntax is "vm.$emit(event, arg)".
The operating environment of this article: Windows 10 system, Vue version 2.9.6, DELL G3 computer.
For the definition of $emit in vue, see:
vm.$emit( eventName, […args] )
Parameters:
{string} eventName
[...args]
Trigger events on the current instance. Additional parameters are passed to the listener callback.
1. Parent components can use props to pass data to child components.
2. Subcomponents can use $emit to trigger custom events of parent components.
vm.$emit(event, arg) //Trigger events on the current instance
vm.$on(event, fn);//Run fn after listening to the event event;
Subcomponent
<template> <div class="train-city"> <h3>父组件传给子组件的toCity:{{sendData}}</h3> <br/><button @click='select(`大连`)'>点击此处将‘大连’发射给父组件</button> </div> </template> <script> export default { name:'trainCity', props:['sendData'], // 用来接收父组件传给子组件的数据 methods:{ select(val) { let data = { cityname: val }; this.$emit('showCityName',data);//select事件触发后,自动触发showCityName事件 } } } </script>
Parent component:
<template> <div>父组件的toCity{{toCity}}</div> <train-city @showCityName="updateCity" :sendData="toCity"></train-city> <template> <script> import TrainCity from "./train-city"; export default { name:'index', components: {TrainCity}, data () { return { toCity:"北京" } }, methods:{ updateCity(data){//触发子组件城市选择-选择城市的事件 this.toCity = data.cityname;//改变了父组件的值 console.log('toCity:'+this.toCity) } } } </script>
[Related recommendation: "vue.js Tutorial"]
The above is the detailed content of What is the usage of emit in vue. For more information, please follow other related articles on the PHP Chinese website!