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='select(`大连`)'>大连</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!