You may have an infinite update loop in a component
学习借鉴自:https://segmentfault.com/a/1190000011156865
例如这样一个组件,它里面是用 :checked +
为了能够分组,需要设置它们的 name 属性
为了能够用
<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)">×</button>
</template>
</div>
</template>
<script>
let count = 0;
export default {
data() {
return {
selfIndex: 0,
itemIndex: 0,
}
},
methods: {
getID(increase = true) { // 注意,问题就出在这里
if (increase) {
this.itemIndex++;
}
return `my-component-${this.selfIndex}-${this.itemIndex}`;
},
},
beforeMount() {
this.selfIndex = count;
count++;
}
}
</script>
这里,为了能生成唯一 ID,我选择每次循环都对 vm.itemIndex++,这就会出现前面说的问题,存在隐患。
解决的方案有两种,一种是把 itemIndex 也放在局部变量里,使它不直接关联在组件上;另一种则是写一个全局的唯一 ID 生成函数,然后引用进来。原理都是一样的。重复的部分就不写了,修改后大体如下:
方案一
<script>
let count = 0;
let itemCount = 0; // 把元素计数器放在这里
export default {
methods: {
getID(increase = true) {
if (increase) {
itemCount++;
}
return `my-component-${this.selfIndex}-${itemCount}`;
}
}
};
</script>
方案二
// helper.js 生成唯一 id
let count = 0;
export default function uniqueID(increase = true) {
if (increase) {
count++;
}
return `prefix-${count}`;
}
// 原来的组件
import uniqueID from './helper';
export default {
methods: {
getID(increase = true) {
let id = uniqueID(increase);
return `my-component-${this.selfIndex}-${id}`;
}
}
}