代码之家  ›  专栏  ›  技术社区  ›  Chris Wickham

VueJS数据属性在装入的函数中返回未定义

  •  0
  • Chris Wickham  · 技术社区  · 7 年前

    我还有一个小时就要开始学VueJS了。我使用Axios发出了一个get请求,它按预期返回了一些数据,但是我无法在mounted函数中访问应用程序的数据属性来分配请求的结果。控制台登录到 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);
        })
    }
    
    })
    
    1 回复  |  直到 7 年前
        1
  •  8
  •   Phiter    7 年前

    因为在那个函数中, 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);
      })
    }