Home > Web Front-end > JS Tutorial > body text

What are the uses of $emit in vue?

php中世界最好的语言
Release: 2018-04-28 14:23:35
Original
4979 people have browsed it

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;
Copy after login

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>
Copy after login

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>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!