<template>
  <main>
    <button @click="reSetData">生成唯一随机深色</button>
    <section class="box">
      <div class="colorChunk" v-for="item in data" :key="item" :style="`background-color: ${item.color}`">{{ item.color }}
      </div>
    </section>
  </main>
</template>
<script>
import { reactive, toRefs, nextTick } from "vue";
export default {
  name: "randomColor",
  setup() {
    const BasicState = reactive({
      data: [
        { name: '1' },
        { name: '2' },
        { name: '3' },
        { name: '4' },
        { name: '5' },
        { name: '6' }
      ],
      exist_color: [], // 记录生成
      randomColor(exist_color) {
        let r = Math.floor(Math.random() * 192);
        let g = Math.floor(Math.random() * 192);
        let b = Math.floor(Math.random() * 192);
        let r16 = r.toString(16).length === 1 && r.toString(16) <= "f" ? 0 + r.toString(16) : r.toString(16);
        let g16 = g.toString(16).length === 1 && g.toString(16) <= "f" ? 0 + g.toString(16) : g.toString(16);
        let b16 = b.toString(16).length === 1 && b.toString(16) <= "f" ? 0 + b.toString(16) : b.toString(16);
        let color = '#' + r16 + g16 + b16;
        // 判定是否重复
        if (exist_color.indexOf(color) === -1) {
          return color;
        } else {
          // 重复?调用自身重新随机
          BasicState.randomColor(exist_color);
        }
      },
      configColor() {
        BasicState.exist_color = [];
        let arr = [];
        return new Promise((resolve) => {
          BasicState.data.forEach((ele) => {
            let color = BasicState.randomColor(BasicState.exist_color);
            arr.push({
              name: `第${ele.name}个`,
              color: color
            })
          })
          resolve(arr)
        })
      },
      async reSetData() {
        const result = await BasicState.configColor();
        BasicState.data = result;
      }
    })
    BasicState.reSetData();
    return {
      ...toRefs(BasicState)
    }
  }
}
</script>
<style scoped>
.box{
  display: flex;
  flex-wrap: wrap;
}
.colorChunk {
  height: 200px;
  width: 200px;
  border: 1px solid red;
}
</style>
