VueJS 数据属性在挂载的函数中返回未定义

Chr*_*ham 4 javascript vue.js axios vuejs2

我已经使用 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);
        })
    }
    
})
Run Code Online (Sandbox Code Playgroud)

Phi*_*ter 19

因为在那个函数中,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);
  })
}
Run Code Online (Sandbox Code Playgroud)

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

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);
  })
}
Run Code Online (Sandbox Code Playgroud)