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:
- <template>
- <div class="train-city">
- <span @click='select(`Dalian`)'>Dalian</span>
- </div>
- </template>
- <script>
- export default {
- name:'trainCity',
- methods:{
- select(val) {
- let data = {
- cityname: val
- };
- this.$emit('showCityName',data);//After the select event is triggered, the showCityName event is automatically triggered
- }
- }
- }
- </script>
Parent component:
- <template>
- <trainCity @showCityName="updateCity" :index="goOrtoCity"></trainCity> //Listen to the showCityName event of the child component.
- <template>
- <script>
- export default {
- name:'index',
- data () {
- return {
- toCity:"Beijing"
- }
- }
- methods:{
- updateCity(data){//Trigger subcomponent city selection - select city event
- this.toCity = data.cityname;//Change the value of the parent component
- console.log('toCity:'+this.toCity)
- }
- }
- }
- </script>