【问题标题】:How do I properly push JSON array onto existing data array in Vue JS on a Axios response?如何在 Axios 响应上将 JSON 数组正确推送到 Vue JS 中的现有数据数组中?
【发布时间】:2018-11-17 10:49:55
【问题描述】:

我认为这是一个通用的 Javascipt 问题,但是我在 Vue Js、Laravel 和 Axios 中工作。

如何将一个 JSON 数组推入另一个 JSON 数组?我的问题是,当我将辅助数组推入主数组时,它是嵌套的(见截图)。我需要它作为同一个数组的一部分。

这是一个简单的索引问题吗?我读过 concat 可以实现这一点,但我有一个“加载更多”按钮并希望附加数组并从底部增加大小,所以 push 是合适的. concat 创建一个新数组并替换当前数组,这是不希望的,因为我想维护现有数组并只是增加大小以更顺畅地加载结果,例如在 Pinterest 滚动和底部填充的新结果。

(这是用于说明问题的简化代码)

要开始的数据属性空数组:

    data () {
        return {
            articles: [],
        }
    },

首先,在页面加载时,articles 数组会填充 JSON 数据。

created() {
    axios.get(url)
        .then(response => {
            this.articles = response.data.data;
    });
},

然后,我想通过方法“加载更多”结果

loadMore() {
    axios.get(url)
        .then(response => {

            console.log('article\'s array data')
            console.log(this.articles)

            this.articles.push(response.data.data)

            console.log('new response array data')
            console.log(response.data.data)

            console.log('the updated array with pushed response array')
            console.log(this.articles)

    });
}

控制台日志

如果正确附加,这应该是一个 5 + 5 = 10 的数组,用于文章数组的长度。

两个响应都是正确的并且匹配 json,因为我已经通过 concat 进行合并。但不可取,因为它会重新加载整个数组。

【问题讨论】:

  • 有很多解决方案,但它们都归结为concat() 以及更多代码。你能更好地解释为什么concat creates a new array and replaces current, which isn't desired as I want to maintain the existing array and just increase size for smoother loading of results 在这种情况下不好吗?我怀疑它会阻碍顺利加载。保留完全相同的数组的唯一方法是将新元素一个一个地推送到它,这是最慢的解决方案。所以我不明白你反对.concat()的论点。
  • 我的论点很差,我只是不确定它是最好的还是正确的。因为阅读这表明“concat”将数组替换为新数组,但我想保持当前数组有效。因此,它不会重新绘制更新。 w3schools.com/jsref/jsref_concat_array.asp

标签: javascript laravel vue.js axios


【解决方案1】:

如果您反对 .concat,这是一种超级简单且高效的方式,您可以尝试以下方法:

const myArray = [1,3,4,5];
myArray.push(...[6,7,8,9);
console.log(myArray); // this will contain [1,2,3,4,5,6,7,8,9] now

【讨论】:

    【解决方案2】:

    取自上述@noa-dev 和@Shilly 的建议——我使用了如下的concat。必须在 var 中为 promise 设置响应,因为没有它就无法工作。谢谢。

    var new_array = response.data.data
    this.articles = this.articles.concat(new_array)
    

    解释 Vue 在使用 concat 时实际上并没有替换数组! :) https://vuejs.org/v2/guide/list.html#Replacing-an-Array

    【讨论】:

      猜你喜欢
      • 2018-07-25
      • 2014-10-11
      • 2019-08-18
      • 1970-01-01
      • 2022-06-14
      • 2022-08-23
      • 2015-03-31
      • 1970-01-01
      • 2019-04-25
      相关资源
      最近更新 更多