Vue.js 在方法内失去范围

Vue.js losing scope inside method

本文关键字:失去 范围 方法 js Vue      更新时间:2023-09-26

我有一个组件,它在创建数据时请求数据。但是,当返回数据时,我无法访问此内容或直接父级范围内的任何内容。

// 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。