<template>
  <div class='roulette'>
    <div class='roulette-wheel' :style="{transform: 'rotate(' + rotateDegrees + 'deg)'}">
      <div class='roulette-item' v-for='(item, index) in items' :key='index' :style="{transform: 'rotate(' + item.rotateDegrees + 'deg)'}">
        <div class='roulette-item-content'>{{ item.content }}</div>
      </div>
    </div>
    <button class='roulette-button' :disabled='isSpinning' @click='spin'>SPIN</button>
  </div>
</template>
<script>
import { ref } from 'vue';

export default {
  name: 'Roulette',
  props: {
    items: {
      type: Array,
      required: true
    },
    spinDuration: {
      type: Number,
      default: 3000
    }
  },
  setup(props) {
    const rotateDegrees = ref(0);
    const isSpinning = ref(false);

    const spin = () => {
      if (isSpinning.value) return;
      isSpinning.value = true;

      const itemDegrees = 360 / props.items.length;
      const randomIndex = Math.floor(Math.random() * props.items.length);
      const targetDegrees = itemDegrees * randomIndex + itemDegrees / 2 + 360 * 5;

      const animation = rotateDegrees.value % 360 === 0 ? 'ease-out' : 'ease-in-out';
      rotateDegrees.value = targetDegrees;

      setTimeout(() => {
        isSpinning.value = false;
        alert(`You won ${props.items[randomIndex].content}!`);
      }, props.spinDuration);
    };

    return {
      rotateDegrees,
      isSpinning,
      spin
    };
  }
};
</script>
<style scoped>
.roulette {
  position: relative;
  width: 200px;
  height: 200px;
}

.roulette-wheel {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.roulette-item {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 18px;
  color: #fff;
  background-color: #f00;
  border-radius: 50%;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
}

.roulette-button {
  position: absolute;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  padding: 10px 20px;
  font-size: 16px;
  background-color: #fff;
  border: 2px solid #f00;
  border-radius: 5px;
  color: #f00;
  cursor: pointer;
}

.roulette-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}
</style>
<p>此组件可以接收一个包含转盘选项的数组和转盘旋转时间的属性。通过点击SPIN按钮,可以在给定的时间内旋转转盘,并在停止时随机选中一个选项。在此示例中,使用了Vue3的'ref'属性来实现响应式数据,以及'setup'函数来处理组件的逻辑。</p>
Vue3 转盘组件代码示例 - 构建交互式游戏元素

原文地址: https://www.cveoy.top/t/topic/niGY 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录