Hello!
I am used to split my code as follows in order to have some basic separation of concerns:
var Vue = require('vue')
module.exports.save function(name) {
return Vue.http.post('/foo/', {
name: name
});
}
var service = require('./service/foo-service')
var app= new Vue({
data : {
foos: [],
},
methods : {
save: function(name) {
service.save(name).then(function(resp) {
this.foos.push(resp.foo)
}
}
}
}
Since the $http.post is decoupled and called globally, the this from the callback is pointing to the window object. Of course, this doesn't happen if the resource is called from the method itself.
Is there a way to access the current Vue instance while working with the global version of the http service? If not, is there a best practice / preferred way to decouple service calls from the component / VM logic?
Great work with this project!
Thank you!
Just store VM instance in local variable, in your method, so you can access it in the service callback. Or .bind(this) to the callback.
.bind(this) seem to be the more robust approach since I'm trying to avoid local boilerplate for this.
Thanks you!
@ionutvelicu If you want to use ES6 you can get this binding using the arrow function syntax:
service.save(name).then((resp) => {
this.foos.push(resp.foo)
});
Great point @steffans! Thanks for your help & effort!
How to get this in vue-resource@next ?
Most helpful comment
@ionutvelicu If you want to use ES6 you can get
thisbinding using the arrow function syntax: