Vue组件-霓虹灯:技术解析与实现
本文将详细解析如何使用Vue 3实现一个动态炫彩霓虹灯效果。
预览
概述
此Vue组件创建了一个由7个同心圆环组成的霓虹灯效果,每个圆环具有彩虹中的一种颜色(红、橙、黄、绿、蓝、靛、紫)。这些圆环的颜色会动态轮转变化,产生向外流动的视觉效果。
实现代码
<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'const colors = ['#ff0000', // 红色'#ff7f00', // 橙色'#ffff00', // 黄色'#00ff00', // 绿色'#0000ff', // 蓝色'#4b0082', // 靛蓝'#9400d3' // 紫色
]const currentColors = ref([...colors])
const animationInterval = ref(null)function rotateColors() {// 颜色轮转currentColors.value.push(currentColors.value.shift())
}function start() {if (!animationInterval.value) {animationInterval.value = setInterval(rotateColors, 100) // 变化间隔}
}function stop() {if (animationInterval.value) {clearInterval(animationInterval.value)animationInterval.value = null}
}onMounted(() => {start() // 默认自动开始
})onBeforeUnmount(() => {stop() // 组件卸载时清除定时器
})// 暴露方法给父组件
defineExpose({start,stop
})
</script><template><div class="neon-container"><divv-for="(color, index) in currentColors":key="index"class="neon-ring":style="{'--ring-color': color,'--ring-size': `${(7 - index) * 50}px`,'--inner-size': `${(6 - index) * 50}px`}"></div></div>
</template><style scoped>
.neon-container {position: relative;width: 400px;height: 400px;display: flex;justify-content: center;align-items: center;
}.neon-ring {position: absolute;border-radius: 50%;width: var(--ring-size);height: var(--ring-size);background: var(--ring-color);box-shadow: 0 0 10px var(--ring-color),0 0 20px var(--ring-color);transition: background 0.3s ease, box-shadow 0.3s ease;
}.neon-ring::after {content: '';position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);width: var(--inner-size);height: var(--inner-size);background: #000;border-radius: 50%;
}
</style>
技术解析
1. ref
currentColors
存储当前颜色数组animationInterval
存储定时器引用
2. 颜色算法
function rotateColors() {currentColors.value.push(currentColors.value.shift())
}
这个简单的算法实现了颜色循环效果:
shift()
移除数组第一个元素push()
将移除的元素添加到数组末尾- 结果是颜色数组不断"轮转"
3. 定时器控制
function start() {if (!animationInterval.value) {animationInterval.value = setInterval(rotateColors, 100)}
}function stop() {if (animationInterval.value) {clearInterval(animationInterval.value)animationInterval.value = null}
}
- 使用
setInterval
每100毫秒调用一次rotateColors
- 提供
start
和stop
方法控制动画,并通过defineExpose
暴露给父组件
4. CSS实现霓虹效果
.neon-ring {/* ... */box-shadow: 0 0 10px var(--ring-color),0 0 20px var(--ring-color);transition: background 0.3s ease, box-shadow 0.3s ease;
}
霓虹效果主要通过CSS实现:
- box-shadow:创建发光效果,两层阴影增强立体感
- transition:使颜色变化更平滑
- 伪元素:
:after
创建黑色内圆,形成圆环效果
5. 动态样式绑定
<divv-for="(color, index) in currentColors":key="index"class="neon-ring":style="{'--ring-color': color,'--ring-size': `${(7 - index) * 50}px`,'--inner-size': `${(6 - index) * 50}px`}"
></div>
- v-for:循环渲染7个圆环
- 动态样式:通过
:style
绑定CSS变量--ring-color
:当前颜色--ring-size
:圆环大小,从大到小(350px到50px)--inner-size
:内圆大小,形成圆环厚度