The usage of $emit in vue

1. Parent components can use props to pass data to child components.
2. The child component can use $emit to trigger the custom event of the parent component.


vm.$emit( ​​event, arg ) // Trigger the event on the current instance

vm.$on( event, fn );// Run fn after listening to the event event; 


For example: child component:

[plain]  view plain copy  
  1. <template>  
  2.   <div class="train-city">  
  3.     <span @click='select(`Dalian`)'>Dalian</span>  
  4.   </div>  
  5. </template>  
  6. <script>  
  7. export default {  
  8.   name:'trainCity',  
  9.   methods:{  
  10.     select(val) {  
  11.       let data = {  
  12.         cityname: val  
  13.       };  
  14.       this.$emit('showCityName',data);//After the select event is triggered, the showCityName event is automatically triggered  
  15.     }  
  16.   }  
  17. }  
  18. </script>  

Parent component:

[plain]  view plain copy  
  1. <template>  
  2.     <trainCity @showCityName="updateCity" :index="goOrtoCity"></trainCity> //Listen to the showCityName event of the child component.  
  3. <template>  
  4. <script>  
  5. export default {  
  6.   name:'index',  
  7.   data () {  
  8.    return {  
  9.       toCity:"Beijing"  
  10.     }  
  11.   }  
  12.   methods:{  
  13.     updateCity(data){//Trigger subcomponent city selection - select city event    
  14.       this.toCity = data.cityname;//Change the value of the parent component  
  15.       console.log('toCity:'+this.toCity)        
  16.     }  
  17.   }  
  18. }  
  19. </script>  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324778726&siteId=291194637