Home  >  Article  >  Web Front-end  >  What are the uses of $emit in vue?

What are the uses of $emit in vue?

php中世界最好的语言
php中世界最好的语言Original
2018-04-28 14:23:355043browse

This time I will show you how to use $emit in vue, and what notesare when using $emit in vue. The following is a practical case, let's take a look.

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 ) //触发当前实例上的事件
vm.$on( event, fn );//监听event事件后运行 fn;

For example: Child component:

<template>  
 <p class="train-city">  
  <span @click=&#39;select(`大连`)&#39;>大连</span>  
 </p>  
</template>  
<script>  
export default {  
 name:'trainCity',  
 methods:{  
  select(val) {  
   let data = {  
    cityname: val  
   };  
   this.$emit('showCityName',data);//select事件触发后,自动触发showCityName事件  
  }  
 }  
}  
</script>

Parent component:

<template>  
  <trainCity @showCityName="updateCity" :index="goOrtoCity"></trainCity> //监听子组件的showCityName事件。  
<template>  
<script>  
export default {  
 name:'index',  
 data () {  
  return {  
   toCity:"北京"  
  }  
 }  
 methods:{  
  updateCity(data){//触发子组件城市选择-选择城市的事件   
   this.toCity = data.cityname;//改变了父组件的值  
   console.log('toCity:'+this.toCity)     
  }  
 }  
}  
</script>

The result is:

toCity: Dalian

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

jQuery implements mouse click suspension effect

JS implements text font printing interface

The above is the detailed content of What are the uses of $emit in vue?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn