Vue随机生成唯一深色

Vue随机生成唯一深色

演示

核心代码

<template>
  <main>
    <h1>App.vue</h1>
    <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} 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() {
        // 异步设置数据,防止forEach循环数据没有处理完成
        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>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值