简体   繁体   English

将数据从组件传递给父级

[英]Passing data from Component to parent

I have created a simple component that displays a SELECT tag.我创建了一个显示 SELECT 标记的简单组件。 On making a selection, I want to pass the selected value to parent (Vue).在进行选择时,我想将所选值传递给父级(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.在 vue 对象中,我有这样的 selectedPeriodChanged() 方法。

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 .当我在 中进行选择时, periodChanged() 方法会触发,并且我在组件的selectedPeriod中获得所选值。 However, I am unable to emit the event to the parent.但是,我无法将事件发送给父级。 (Parent's selectedPeriodChanged() never fires) I don't see any errors. (父母的 selectedPeriodChanged() 永远不会触发)我没有看到任何错误。 What's wrong in my code?我的代码有什么问题? Thanks.谢谢。

Because HTML attributes are case insensitive, the event name should be kebab-case in the template instead of camelCase.因为 HTML 属性不区分大小写,所以模板中的事件名称应该是 kebab-case 而不是 camelCase。 See: https://v2.vuejs.org/v2/guide/components.html#camelCase-vs-kebab-case见: https ://v2.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这是一个工作小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM