我正在尝试在 Vue.js 中创建一个简单的插件来包装vue-resource
插件以跟踪请求的状态。
function State() {}
State.prototype.post = function (ctx, name, url, data, successCB, errorCB) {
var options = {};
if (errorCB) {
options.error = function (resp) {
ctx[name] = 'error';
return errorCB(resp);
};
}
ctx[name] = 'sending';
ctx.$http.post(url, data, function (res, code, req) {
ctx[name] = 'sent';
return successCB(res, code, req);
}, options);
};
function install(Vue) {
Object.defineProperties(Vue.prototype, {
$state: {
get: function () {
return new State;
// return Vue.state.bind({$vm: this});
}
}
});
}
module.exports = install;
你会看到我ctx
从调用 Vue 传递上下文来访问它的data
值。我已经看到vue-resource
插件有一种方法可以通过插件自动绑定它 bat 不能完全正确地获取语法。
基本上我想避免ctx
每次都传递上下文,它应该已经有了正确的上下文。
编辑
为了澄清,我正在寻找一种解决方案来传递正确的上下文。上面只是一个例子,我不是在寻找跟踪状态的解决方案。
例如在vue-resource
插件中,如果我们发出任何 http 请求。
this.$http.get('/some/url', {}, function () {
this.func();
console.log(this.var);
});
回调中已经存在上下文。我不需要做一些事情var _this = this
来进入视图范围。我想为我的插件实现同样的效果,这样合适this
的就在那里。我试图从vue-resource
插件中找出答案,但很难遵循所有代码。