【问题标题】:Erro when trying to push to array from http request in vue.js尝试从 vue.js 中的 http 请求推送到数组时出错
【发布时间】:2020-05-04 20:36:19
【问题描述】:

我正在尝试将对象推送到来自 axios 获取请求的响应中,但我总是收到“推送不是函数”错误

我正在尝试在 http 请求的 .then 块内推送

ps:我正在关注 vuejs 网站上的示例

var app = new Vue({
    el: '#app',
    data: {
        message: 'Hello Vue!',
        bitCoinValue: null
    },
    mounted() {
        this.getBitcoinValue();
    },
    filters: {
        currencydecimal(value) {
            return value.toFixed(2);
        } 
    },
    methods: {
        getBitcoinValue: function () {
            axios.get('https://api.coindesk.com/v1/bpi/currentprice.json')
                .then(response => {
                    this.bitCoinValue = response.data.bpi || [];
                    this.bitCoinValue.push({code: 'BRL', description: 'Reais', symbol: 'R$', rate_float: 25.50});
                });
        }
    }
})

这是错误信息:

Uncaught (in promise) TypeError: this.bitCoinValue.push is not a function 在 site.js:21

【问题讨论】:

  • 初始化你的bitCoinValue为空array而不是null

标签: javascript vuejs2 axios


【解决方案1】:

问题是您从https://api.coindesk.com/v1/bpi/currentprice.json 响应bpi 条目是Object,因此您不能使用push,因为它是Array Object 的函数。

你有两个选择:

  1. 将您的值设置为 api 响应的类似方法

    getBitcoinValue: function () {
        axios.get('https://api.coindesk.com/v1/bpi/currentprice.json')
            .then(response => {
                this.bitCoinValue = response.data.bpi || [];
                this.bitCoinValue['BRL'] = {code: 'BRL', description: 'Reais', symbol: 'R$', rate_float: 25.50};
            });
    }
    
  2. 将对象转换为数组然后推送

    getBitcoinValue: function () {
        axios.get('https://api.coindesk.com/v1/bpi/currentprice.json')
            .then(response => {
                let objectResponse = response.data.bpi || {};
                this.bitconValue = Object.values(objectResponse).map(item => item)
                this.bitCoinValue['BRL'] = {code: 'BRL', description: 'Reais', symbol: 'R$', rate_float: 25.50};
            });
    }
    

【讨论】:

    【解决方案2】:

    在浏览器中打开您的 API 端点,我发现响应 JSON 中的 "bpi" 键不是数组而是对象。因此,您需要直接设置密钥,而不是.push() 值,即this.bitCoinValue.BRL = {...};

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多