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
You can force-reload components by adding :key="$route. fullPath". However, :key="$route. fullPath" only can force-reload the components of the different route but not the components of the same route.
The best way to force Vue to re-render a component is to set a :key on the component. When you need the component to be re-rendered, you just change the value of the key and Vue will re-render the component.
Conditional rendering refers to the ability to render distinct user interface (UI) markup based on whether a condition is true or not. This notion is frequently used in contexts like showing or hiding components (toggling), switching application functionality, handling authentication and authorization, and many more.
VueJS props are the simplest way to share data between components. Props are custom attributes that we can give to a component. Then, in our template, we can give those attributes values and — BAM — we're passing data from a parent to a child component!
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With