【问题标题】:VueJS data property returns undefined in mounted functionVueJS 数据属性在挂载函数中返回未定义
【发布时间】:2018-08-20 11:24:20
【问题描述】:

我使用 Axios 发出了一个 get 请求,该请求按预期返回了一些数据,但我无法在挂载函数中访问应用程序的数据属性来分配请求的结果。到this.productList 的控制台日志返回undefined。谁能指出我正确的方向?

new Vue({
    el: '#products',
    data: function(){
        return{
            test: 'Hello',
            productList: null
        }
    },
    mounted: function(){
        axios.get('https://api.coindesk.com/v1/bpi/currentprice.json').then(function(response){
            console.log(response.data);
            console.log(this.productList)
        }).catch(function(error){
            console.log(error);
        })
    }
    
})

【问题讨论】:

标签: javascript vue.js vuejs2 axios


【解决方案1】:

因为在那个函数中,this 没有引用你的 vue 实例。它还有另一个含义。

您可以在外部函数中创建一个临时变量来保存this 的值,如下所示:

mounted: function() {

  let $vm = this;

  axios.get('https://api.coindesk.com/v1/bpi/currentprice.json').then(function(response) {
    console.log(response.data);
    console.log($vm.productList)
  }).catch(function(error) {
    console.log(error);
  })
}

或者你可以使用更好的箭头函数:

mounted: function() {

  axios.get('https://api.coindesk.com/v1/bpi/currentprice.json').then((response) => {
    console.log(response.data);
    console.log(this.productList)
  }).catch(function(error) {
    console.log(error);
  })
}

【讨论】:

  • 感谢您的回答。为什么使用箭头函数会改变“this”引用的内容?
  • 签出this
  • 您的答案在我的情况下有效,因为我将“this”分配给了一个变量,但您能解释一下它是如何工作的
  • @MohammadFahadRao this 是一个保留变量,取决于它所访问的范围。如果您尝试在内部函数中访问this,它将具有与外部函数中不同的值。通过将父作用域中的this 归因于变量,您可以在内部作用域中访问它。
猜你喜欢
  • 2016-02-04
  • 2021-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-07
  • 2015-04-22
  • 1970-01-01
  • 2020-02-02
相关资源
最近更新 更多