Home » vue » Passing data from Component to parent

Passing data from Component to parent

Posted by: admin November 26, 2021 Leave a comment

Questions:

I have created a simple component that displays a SELECT tag. On making a selection, I want to pass the selected value to parent (Vue). This is the component code:

// Period Selection 
Vue.component ('period-component', {
    props: [],
    data () {
        return {
            periods: [
                { text: '-- Select --', value: ''},
                { text: 'Today', value: 'Today'},
                { text: 'Up to Last 7 Days', value: '7D'},
                { text: 'Up to Last 30 Days', value: '30D'},        
                { text: 'Up to 3 Months', value: '3M'},             
                { text: 'Up to 6 Months', value: '6M'},             
                { text: 'Up to 1 Year', value: '1Y'},                       
                { text: 'All', value: '1Y'},                                
            ],
            selectedPeriod:false,
        }
    },      
    methods: {
        periodChanged() {
            console.log('In periodChanged.' ,this.selectedPeriod);  
            this.$emit('periodChangedEvent', this.selectedPeriod);
        },
    },
    template: `<div>
        <select 
            v-model="selectedPeriod"
            v-on:change="periodChanged()">
            <option 
                v-for="period in periods" 
                :value="period.value">{{ period.text }}
            </option>
        </select>
    </div> `
})

I use the component in the folloing way:

<period-component 
   v-on:periodChangedEvent="selectedPeriodChanged($event)" >
</period-component>

In the vue object, I have the selectedPeriodChanged() method like this.

selectedPeriodChanged: function(value){
  console.log('in periodChanged' );
},

When I make selection in , the periodChanged() method fires and I get the selected value in component’s selectedPeriod. However, I am unable to emit the event to the parent. (Parent’s selectedPeriodChanged() never fires) I don’t see any errors. What’s wrong in my code? Thanks.

Answers:

Because HTML attributes are case insensitive, the event name should be kebab-case in the template instead of camelCase. See: https://vuejs.org/v2/guide/components.html#camelCase-vs-kebab-case

<period-component v-on:period-change-event="selectedPeriodChanged($event)"></period-component>

this.$emit('period-change-event', this.selectedPeriod);

Here is a working fiddle