首页 > 解决方案 > 承诺中的“这个”指的是什么?(示例 (Vue) - 无法从 API 响应中设置数据)

问题描述

我正在探索 vue 和新的 javascript 工具——事情对我来说有点令人费解,因为我很难调试和理解正在发生的事情。

我正在尝试通过一个简单的 API 获取数据,使用这里建议的 axios: https ://vuejs.org/v2/cookbook/using-axios-to-consume-apis.html#Real-World-Example-Working-with -数据

事实证明,如果我使用“普通”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
                      }
              )


   }

} 

你能解释一下为什么吗?

我帮助自己回答了: “this”在 ES6 中的箭头函数中指的是什么? - “这指的是封闭的上下文”:

您是否介意提出一些工作实践来保持代码简洁明了?

我来自使用本机 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,例如封装的函数:

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

标签: javascriptvue.jsthisaxios

解决方案


推荐阅读