首页 > 解决方案 > 尝试从 vue.js 中的 http 请求推送到数组时出错

问题描述

我正在尝试将对象推送到来自 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 at site.js:21

标签: javascriptvuejs2axios

解决方案


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


推荐阅读