change other element in array with the same value

Viewed 37
<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>

When I load the page and click the image, I see changes in two elements in the array because they have the same value but a different index. I think that's because I pushed the same array. I also tried Array.from() and the spread operator.

1 Answers

In response.data.concat(response.data), you're appending the original objects by reference, so changes to one instance affect the other as they refer to the same data.

Assuming the data items are all shallow, a quick way to clone the data is to map them into new objects:

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

demo

Related