Vue.js 在方法内失去范围
Vue.js losing scope inside method
我有一个组件,它在创建数据时请求数据。但是,当返回数据时,我无法访问此内容或直接父级范围内的任何内容。
// Service
class DataService {
getDataFromService() {
var p = new Promise(function(resolve, reject) {
resolve({ message: 'hello world' });
});
return p;
}
}
var dataService = new DataService();
// Component
Vue.component('review', {
created: function() {
this.fetchData();
},
methods: {
fetchData: function() {
var that = this;
var hello = 'world';
// normal function
dataService.getDataFromService().then(function(data) {
this.foo = data.message; // 'this' is undefined
that.bar = data.message; // 'that' is undefined
console.log(hello); // 'hello' is undefined
});
// fat arrow
dataService.getDataFromService().then((data) => {
this.foo = data.message; // 'this' is undefined
that.bar = data.message; // 'that' is undefined
console.log(hello); // 'hello' is undefined
});
},
},
});
在上面的例子中,"这个"和"那个"都是未定义的,我不确定为什么。我正在使用 babel & browserify 来编译代码。
我尝试更改服务以使用回调而不是没有改变任何内容的承诺。我还尝试使用普通的"函数(数据)"而不是胖箭头函数。
更新:该示例适用于 JSFiddle!我猜这意味着它与 babel/browserify/modules 有关。
使用箭头函数消除了块作用域,使用回调函数你必须使用 self = this 才能使用它,但不要在箭头函数中运行此脚本,看看发生了什么:
var cb= function(f){
f();
}
var fetchData = function() {
var that = this;
this.data ='data';
cb( () => {
console.log('---')
console.log(data);
console.log(that);
});
}
我最终切换到了阻止问题发生的 webpack。
相关文章:
- 正在全局范围中查找JavaScript函数
- 如何通过数组更新角度子范围
- 如何使用ngrepeat和双向绑定获得指令的隔离范围
- HTML范围:动态设置值属性
- Javascript游戏输入失去焦点
- "实例范围”;TypeScript类的getter/setter
- jquery日期选择器年份范围默认值
- jquery日期选择器失去了交互性
- Jpgraph:如何手动设置X轴和Y轴的范围
- 在对象数组中查找多个值的d3范围
- 动态加载angularjs并生成控制器和范围
- 如何通过谷歌应用程序脚本从谷歌文档中的位置确定命名范围
- 在Materialize Calendar中设置年份范围
- 在MVVM视图模型中处理应用程序范围的元素
- Vue.js 在方法内失去范围
- 失去与 async.waterfall 的范围
- Javascript模块模式-失去了这个范围
- 试验失去范围
- 角2.在Promise中失去了这个范围
- 在ng-repeat中失去控制范围