【问题标题】:How do I pass data from my function to the data method?如何将数据从我的函数传递到数据方法?
【发布时间】:2021-05-17 03:12:27
【问题描述】:

我正在尝试将数据从我的 API 传递到 Vue 中的 data 方法。


       data(){
          return{
            name:"" 
          }
       },
           
    
       methods: {    
        
              getData(){
                useData.data("profile",  this.route.params.id).then(function(r: any){          
                   r.data;         
                });
              }

        },
    
        created(){
        
          this.name=this.getData();
        
        }

我在我的模板中显示它是这样的:

{{name}}

问题是它不起作用。它没有显示任何错误,但也没有显示任何内容。

如果我将函数 getData() 更改为:

      getData(){
         return "123";
      }

成功在模板中显示123。我相信这与承诺有关。

如果我尝试直接在函数 getData() 内为 name 赋值,我会收到以下错误:

Uncaught (in promise) TypeError: Cannot set property 'name' of 未定义

那么如何从 http 请求中获取数据并将其发送到data 方法?

【问题讨论】:

  • 如果你想像你一样分配name,你的getData方法需要return
  • 谢谢,但我试过了。没用。
  • 因为它是一个承诺。返回值需要await

标签: vue.js ionic-framework promise


【解决方案1】:

我只是通过改变解决了这个问题

来自

getData(){
   useData.data("profile",  this.route.params.id).then(function(r: any){          
         r.data;         
   });
}

 getData(){
    useData.data("profile",  this.route.params.id).then(r =>{          
        this.name=r.data;         
    });
 }

我猜this 不适用于常规函数

如果有人知道是否有任何方法可以在常规函数中使用 this,请告诉我如何使用。

【讨论】:

  • 好的,但这不仅仅是修复原始代码。
  • 我想知道一种修复原始代码的方法。哈哈哈,如果你有什么想法...因为我实际上只是想将数据从我的函数 getData 传递给 Vue 的 data 方法...不管怎样。但它奏效了。
猜你喜欢
  • 2019-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-14
  • 2020-07-04
  • 1970-01-01
  • 1970-01-01
  • 2011-11-05
相关资源
最近更新 更多