Search code examples
vue.jsvuejs2vue-componentvue-select

Can't access to data from my method


I've been trying to access my "selected" data from my method "itemChange" without any luck at all.
The error I got is "this.selected is undefined"

My question is how can I access from my method to my component data?

My component implementation

import VueSelect from 'vue-select';

Vue.component('v-select', VueSelect);
        Vue.component('club-type',{
            template: "#club-type",
            props: ['options'],

        data: {
                selected: {title: 'My title', logo: 'logo here', info: 'info here'}
        },
        methods: {
            itemChange: function () {
                console.log("msg: " + this.selected['title']);
            }
        }
    });

My template

<script type="text/x-template" id="club-type">

                <v-select :options="options" label="title" :on-change="itemChange" :searchable="false" v-model="selected">

                    <template slot="option" scope="option">
                        <div class="float-left-items">
                            <div class="club-type-thumb" v-if="option.logo"><img v-bind:src="option.logo"></div>

                            <div class="club-type-title">{{ option.title }} <br/> <span class="pill club-type-pill"> AGE {{ option.age }}</span></div>
                        </div>
                    </template>
                </v-select>
</script>

In my template above, if I add v-model="selected" it show an error "selected is undefined."


Solution

  • First, you need to return your data :

    data () {
      return {
        selected: { title: 'My title', logo: 'logo here', info: 'info here' }
      }
    },
    

    Then, it’s not an array, so you can’t access it like you tried in your method. You have to call it as a property.

    this.selected.title
    

    EDIT: As stated by @Phil, this second point is not required.