promise中的“ this”指的是什么? (示例(Vue)-无法通过API响应设置数据)

时间:2019-01-13 14:17:33

标签: javascript vue.js this axios

我正在探索vue和新的javascript工具-从某种意义上来说,我感到有些困惑,因为我很难调试并了解正在发生的事情。

我正尝试通过一个简单的API使用axios来获取数据,如下所示: https://vuejs.org/v2/cookbook/using-axios-to-consume-apis.html#Real-World-Example-Working-with-the-Data

事实证明,如果我使用“普通” javascript,将不会设置数据。

它必须与解释“ this”元素有关。

相反,如果我使用箭头功能,则会设置数据。

data () {
  return {
     query : {
        info : null
     }          
}

methods : {

   test : function(query) {
             params = {
               origin : '*',
               action : 'query',   
               prop : 'pageimages',
               pithumbsize : 400,
               pilimit : 'max',
               list : 'search',
               srsearch : query,
               utf8 : true,
               format : 'json'

              }

              axios.get('https://en.wikipedia.org/w/api.php', {
                params : params 
              })
              .then(function (response) {

                // won't work :     this.query.info // undefined        

                this.query.info = response.data.query.search

              })
              .then( 
               // this.query.info is set
               response => {
                        this.query.info = response.data.query.search
                      }
              )


   }

} 

你能解释为什么吗?

我帮助自己解答了: What does "this" refer to in arrow functions in ES6?-“这是指封闭的上下文”:

  • this在模式then(function(response){ this.[...])和模式then( response => this.[...])中指的是什么?

  • 我该如何使用不带箭头功能的语法,并使用this引用vue的data()模型?

您还介意提出一些工作习惯,以保持代码简洁明了吗?

我来自使用本机javascript和jquery,尽管有些冗长,但我可以很好地理解正在发生的事情并轻松调试。

使用这些新工具代替了这些新工具,尽管功能强大,但我似乎有点迷茫,因为似乎有很多其他工具可以用来完成任务。

在学习的同时,我仍然更愿意编写一些冗长的代码并使用Web控制台进行调试,而不是必须由框架编译的节点插件和语法。

__

已编辑

在评论后,我尝试了:

            .then(function(response){

            // won't work : here thisArg should be the vue app,
            // so self.query.info should bind to 
            // [App data()].query.info 
            // still, query.info is undefined
            // though response was successfully fetched

            var self = this

            self.query.info = response.data.query.search
          })

已编辑2 (答案)

我发现此答案有帮助: https://stackoverflow.com/a/29881419/305883

因此我意识到上述模式是错误的,因为在then()中编写var self = this意味着我仍在引用未定义的promise对象的this。

因此,使用“正常”功能,我应该写类似的东西:

var self = this; // now self is referenced to the external object, the Vue app

              fetchResponseFromApi(query)
              .then(function(response){

                self.query.info = response.data.query.search
              }) 

这个答案解决了我的问题(“ hohoho”:“这个”答案没有双关语。)

在其他答案中,我阅读了一些注释,以免绕过thisArg,例如封装函数:

有关澄清良好编码模式的评论对其他人也有好处。

0 个答案:

没有答案