Extending my comment to the answer -
So, do you have a name
property on your Vue component, and you want this plugin to update this value as the HTTP request progresses? I think this gives you a bad chain of responsibility. Your Vue instance must have a name
property, and your plugin will not be standalone.
It would be better to make the plugin handle all state tracking on its own. You can create a State property called status
that will update as the request progresses. Then you can find out the current state using this.$state.status
. Then the plugin is responsible for this, and the component remains independent
State.prototype.status = "not sent"; State.prototype.post = function (url, data, successCB, errorCB) { var options = {}; if (errorCB) { options.error = function (resp) { this.status = 'error'; return errorCB(resp); }; } this.status = 'sending'; this.Vue.http.post(url, data, function (res, code, req) { this.status = 'sent'; return successCB(res, code, req); }, options); }; function install(Vue) { Object.defineProperties(Vue.prototype, { $state: { get: function () { var state = new State; state.Vue = Vue; return state; } } }); }
Then in html:
<div v-if="$state.status == 'sending'">Sending...</div> <div v-if="$state.status == 'sent'">Sent!</div> <div v-if="$state.status == 'error'">Error!</div>
If you want to do something your own way, I think you just need to bind this
to post()
every time from your Vue component:
this.$state.post(args){ }.bind(this)
So inside post
this
function will be your Vue. I think the best way is best
Edit -
The successCb
and errorCb
already executed in the scope of the Vue component because you defined them there. The vue-resource
callbacks in your situation have a State
scope, because you defined them here, this will not change unless you pass the context as you did. But the point here is that your plugin does not need to know the context of the component, since vue-resource
never knows the context of the component. It just receives the data, sends a request and launches a callback. Never knows anything about the calling component.
So, in the functions that you send to this.$state.post
as callbacks, you can edit your Vue data with this.var
- as you should. In callbacks sent to Vue.http.post
from your state, you can edit the properties of the State
object - again the expected behavior. You need to make the name
or status
variable part of State
, and then reference it as this.$state.name
from your Vue component to check the status.
edit 2:
you could even have the variable $state.response
and go into myCustomVar
and then track $state.response.myCustomVar
. Thus, you can pass different user variables for each request and track them yourself