Reputation: 145
I'm newbie in Vue.js and I'm trying to create without success a simple component that consists in a selectList and I'm trying to fill its options data simulating an Ajax request, this is my code:
HTML
<div id="app">
<my-select></my-select>
</div>
<template id="my-template">
<div>
<select v-model="team">
<option v-for="n in teams" v-bind:value="n.id">
{{n.name}}
</option>
</select>
<p>Selected Team: {{team}}</p>
</div>
</template>
JS
Vue.component("my-select", {
template: "#my-template",
mounted: function() {
this.getTeams().then(function(data) {
this.teams = data;
});
},
data: function() {
return {
team: 0,
teams: []
}
},
methods: {
getTeams: function() {
var d = $.Deferred();
setTimeout(function() {
var teams = [
{id: 1, name: "Real Madrid"},
{id: 2, name: "Bayern München"}
];
d.resolve(teams);
}, 2000);
return d.promise();
}
}
});
new Vue({
el: "#app"
});
My fiddle: https://jsfiddle.net/3ypk60xz/2/
I appreciate any help
Upvotes: 8
Views: 22205
Reputation: 32734
You have a scoping issue. Remember, function()
creates it's own scope when declared anonymously, so this
refers to the function. To get around this either use an arrow function (if using ES6
) or set a variable that points to the correct context: var self = this
:
ES6
mounted: function() {
this.getTeams().then(data => {
this.teams = data;
});
}
ES5
mounted: function() {
var self = this;
this.getTeams().then(function(data) {
self.teams = data;
});
}
Here's your updated fiddle using an arrow function: https://jsfiddle.net/mrvymzgh/
And in ES5: https://jsfiddle.net/mrvymzgh/1/
Upvotes: 8