【问题标题】:Vue.js losing scope inside methodVue.js 在方法内部失去作用域
【发布时间】:2016-08-21 11:08:34
【问题描述】:

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

// 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
      });
    },
  },
});

在上面的示例中,'this' 和 'that' 都未定义,我不知道为什么。我正在使用 babel & browserify 来编译代码。

我尝试将服务更改为使用回调而不是没有改变任何东西的承诺。我还尝试使用普通的“函数(数据)”而不是胖箭头函数。

更新: 该示例适用于JSFiddle!我猜这意味着它与 babel/browserify/modules 有关。

【问题讨论】:

  • 如果你不使用函数字面量,你可能会更轻松,因为你可以访问 ES6 语法。
  • 我已经尝试过标准和粗箭头功能。两者都没有改变。我已更新问题以包含此信息。
  • this 在非箭头函数中的值与that 不同可能是可以理解的,但hello 未定义意味着您的环境中存在严重错误。 JavaScript 中不允许这种行为。
  • 您提供的代码 sn-p 无法完全复制您在 cmets 中列出的输出。变量hello 根本无法记录undefined,因为它在范围内并且没有被任何其他局部变量别名。您提供的小提琴之所以有效,是因为它是正确的(假设 vue 库正确地将fetchDatathis 绑定)。我猜有两件事你没有理解。函数中this的大小写及箭头与函数表达式的区别。
  • 我完全了解范围应该如何工作。是的,它不应该记录未定义,但它是。这就是我发布问题的原因。

标签: javascript promise ecmascript-6 vue.js


【解决方案1】:

使用箭头函数消除了块作用域,使用回调函数必须使用 self = this 才能使用 this,但不能在箭头函数中运行此脚本并查看发生了什么:

                var cb= function(f){
                    f();
                } 


                var fetchData = function() {
                    var that = this;
                    this.data ='data';

                     cb( () => {
                         console.log('---')
                        console.log(data);
                        console.log(that);
                    });
                }

【讨论】:

    【解决方案2】:

    我最终改用 webpack,这阻止了问题的发生。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-09
      • 2015-09-26
      • 2020-12-09
      • 1970-01-01
      • 1970-01-01
      • 2011-01-21
      • 2017-04-02
      • 1970-01-01
      相关资源
      最近更新 更多