0

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."

mana
  • 1,075
  • 1
  • 24
  • 43
  • 3
    Component `data` needs to be a function, eg `data: function() { return { selected: ... } }`. See https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function – Phil Aug 13 '18 at 06:16

1 Answers1

1

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.

EmmanuelBeziat
  • 664
  • 8
  • 23
  • The first part of your answer is correct (could have simply voted to close as a typo but whatever). The second part is incorrect; in JavaScript `this.selected.title` and `this.selected['title']` are equivalent. See https://stackoverflow.com/questions/4968406/javascript-property-access-dot-notation-vs-brackets – Phil Aug 13 '18 at 06:25
  • @Phil Thanks for the tip! – EmmanuelBeziat Aug 13 '18 at 07:10