VueJS数据属性在安装的函数中返回未定义 [英] VueJS data property returns undefined in mounted function

查看:149
本文介绍了VueJS数据属性在安装的函数中返回未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've made a get request using Axios which returns some data as expected, but I cannot access the app's data properties in the mounted function to assign the results of the request. The console log to this.productList returns undefined. Can anyone point me in the right direction?

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);
        })
    }
    
})

推荐答案

由于在该函数中,this并未引用您的vue实例.它有另一种含义.

Because in that function, this doesn't refer to your vue instance. It has another meaning.

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

You can make a temporary variable to hold the value of this in the outer function, like 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);
  })
}

或者您可以使用更好的箭头功能:

Or you can use the nicer arrow functions:

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);
  })
}

这篇关于VueJS数据属性在安装的函数中返回未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆