Home > Enterprise >  rendering the array values only works in the initialization in vue2?
rendering the array values only works in the initialization in vue2?

Time:09-11

I have worked on vue2 with a simple demo, there is an array with values, by clicking the button, the array values will be shuffled. However rendering the array in html doesn't change at all after the shuffling.

<template>
  <div>

      <div @click="random()" > random </div>

      {{ selected11.length }}
      <div  v-for="(item,index) in selected11" :key="index" >
          {{ item }} {{ index }}
      </div>  

  </div>
</template>
<script>
export default {
  name: 'Choice',

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

  created() {
      this.selected11 = ['A', 'B', 'C', 'D','E'];
  },

  methods: {
    random(){
      console.log( 'random',this.selected11 );
      this.selected11 = this.shuffle( this.selected11 );
      console.log( this.selected11 );
    },
    shuffle(a) {
      var j, x, i;
      for (i = a.length - 1; i > 0; i--) {
          j = Math.floor(Math.random() * (i   1));
          x = a[i];
          a[i] = a[j];
          a[j] = x;
      }
      return a;
  }

  }
}
</script>

CodePudding user response:

The issue is in your shuffle method where reassignment of keys with values from key positions of its own referenced self is self-destructive and is causing a silent reactive fail.

The only way I can think of describing this is like a Wormhole is traveling into its self, in this circular event that warps its self out of existence...

You need to shuffle a clone of the original object and return this shuffled clone so it replaces the original object, otherwise the array eats its self.

    shuffle(a) {
      let j, x, i;

      let shuffle = structuredClone(a)

      for (i = shuffle.length - 1; i > 0; i--) {
        j = Math.floor(Math.random() * (i   1));
        x = shuffle[i];
        shuffle[i] = shuffle[j];
        shuffle[j] = x;
      }

      return shuffle;
    }
  • Related