You may have an infinite update loop in a component

Keywords: Attribute

You may have an infinite update loop in a component
Learn from: https://segmentfault.com/a/1190000011156865
For example, in such a component, a set of buttons are implemented with checked +. It has the following functions:

To be able to group, you need to set their name attribute
In order to be able to use the control, you need to set the id
Button can be deleted
So I chose to do this:

<template>
<div>
  <template v-for="(item, index) in items">
    <input type="checkbox" :name="'my-component-' + selfIndex" :id="getID">
    <label :for="getID(false)">
    <button type="button" @click="remove(index)">&times;</button>
  </template>
</div>
</template>

<script>
let count = 0;

export default {
  data() {
    return {
      selfIndex: 0,
      itemIndex: 0,
    }
  },
  methods: {
    getID(increase = true) { // Attention, that's the problem
      if (increase) {
        this.itemIndex++;
      }
      return `my-component-${this.selfIndex}-${this.itemIndex}`;
    },
  },
  beforeMount() {
    this.selfIndex = count;
    count++;
  }
}
</script>

Here, in order to generate a unique ID, I choose to treat vm.itemIndex + + every time I cycle. This will cause the problems mentioned above, and there are hidden dangers.

There are two solutions: one is to put itemIndex in local variables so that it is not directly related to components; the other is to write a global unique ID generation function and then reference it. The principle is the same. The repeated part will not be written. After modification, it is roughly as follows:
Scheme 1

<script>
let count = 0;
let itemCount = 0; // Put the element counter here

export default {
  methods: {
    getID(increase = true) {
      if (increase) {
        itemCount++;
      }
      return `my-component-${this.selfIndex}-${itemCount}`;
    }
  }
};
</script>

Option two

// helper.js generate unique id
let count = 0;
export default function uniqueID(increase = true) {
  if (increase) {
    count++;
  }
  return `prefix-${count}`;
}

// Original components
import uniqueID from './helper';

export default {
  methods: {
    getID(increase = true) {
      let id = uniqueID(increase);
      return `my-component-${this.selfIndex}-${id}`;
    }
  }
}

Posted by shortkid422 on Wed, 18 Dec 2019 11:56:23 -0800