Vue-resource: Access current Vue instance through Global scope.

Created on 2 Mar 2016  路  5Comments  路  Source: pagekit/vue-resource

Hello!

I am used to split my code as follows in order to have some basic separation of concerns:

  • I am creating a service module:
var Vue = require('vue')

module.exports.save function(name) {
  return Vue.http.post('/foo/', {
    name: name
  });
}
  • Then, from my VM / Controller I am using this as follows:
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!

Most helpful comment

@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)
});

All 5 comments

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 ?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Jigsaw5279 picture Jigsaw5279  路  5Comments

Dreampie picture Dreampie  路  3Comments

V-Tom picture V-Tom  路  3Comments

nivv picture nivv  路  4Comments

laizhenhai88 picture laizhenhai88  路  4Comments