【问题标题】:change other element in array with the same value用相同的值更改数组中的其他元素
【发布时间】:2021-02-18 00:25:08
【问题描述】:
<template>
  <el-row>
    <el-col :span="24">
      <el-image
        v-for="(card, index) in randomCards"
        :key="card.indexOf"
        :src="card.url"
        :id="(card.id = index)"
        fit="fill"
        @click="flipCards(index)"
      ></el-image>
    </el-col>
  </el-row>
</template>

<script>
import axios from "axios";
export default {
  data() {
    return {
      selectedCardsId: [],
      randomCards: null,
      data: [],
    };
  },
  computed: {},
  methods: {
    getResults() {
      axios
        .get("https://api.thecatapi.com/v1/images/search", {
          params: { limit: 36 },
        })
        .then((response) => {
          this.randomCards = response.data
            .concat(response.data)
            .sort(() => 0.5 - Math.random());
        });
    },
    flipCards(cardIndex) {
      this.randomCards[cardIndex].url = "1";
    },
  },
  async mounted() {
    await this.getResults();
  },
};
</script>

当我加载页面并单击图像时,我看到数组中的两个元素发生了变化,因为它们的值相同但索引不同。我认为那是因为我推了同一个数组。我还尝试了Array.from() 和扩展运算符。

【问题讨论】:

    标签: javascript arrays vue.js


    【解决方案1】:

    response.data.concat(response.data) 中,您通过引用附加原始对象,因此对一个实例的更改会影响另一个实例,因为它们引用相同的数据。

    假设数据项都是浅的,克隆数据的一种快速方法是将map它们放入新对象中:

    this.randomCards = response.data.concat(response.data.map(x => ({ ...x })))
    

    demo

    【讨论】:

      猜你喜欢
      • 2011-08-22
      • 2021-10-25
      • 1970-01-01
      • 1970-01-01
      • 2016-08-15
      • 1970-01-01
      • 2013-05-28
      • 2021-05-30
      • 2020-12-05
      相关资源
      最近更新 更多