I can't figure out how to execute a function in Vue.js after an $http.get
request has finished. In the following example I want to automatically select an element of foobar
right after page load, but this works only when the alert is there.
new Vue({
el: '#foo',
data: {
foobar: [],
foobar_selected: []
},
ready: function() {
this.fetchFoobar();
alert('silly');
this.selectFoobar(2);
},
methods: {
fetchFoobar: function () {
this.$http.get('foobar_to_fetch', function (foobar_fetched) {
this.foobar = foobar_fetched;
})
},
selectFoobar: function (index) {
this.foobar_selected.push(this.foobar[index]);
}
}
});
-
<div id="foo">
<h2>Foobars</h2>
<table>
<tr v-repeat="foobar">
<td>{{ id }}</td>
<td>{{ name }}</td>
<td><button v-on="click: selectFoobar($index)">select</button></td>
</tr>
</table>
<h2>Selected Foobars</h2>
<table>
<tr v-repeat="foobar_selected">
<td>{{ id }}</td>
<td>{{ name }}</td>
</tr>
</table>
</div>
It says here https://github.com/vuejs/vue-resource that the third argument of get
is success
, but I don't understand how I am supposed to use it in this case. At least this works:
this.$http.get('foobar_to_fetch', function (foobar_fetched) {
this.foobar = foobar_fetched;
}, alert('useless'));
But this does not:
this.$http.get('foobar_to_fetch', function (foobar_fetched) {
this.foobar = foobar_fetched;
}, this.selectFoobar(2));
What is the correct way to do this in Vue.js?
I am using Vue 0.11.10 and Vue-resource 0.1.16.