vue实现发廊灯效果
Vue 实现发廊灯效果
发廊灯效果通常指一种彩色灯光循环变化的视觉效果,常见于霓虹灯或广告牌。以下是基于 Vue 的实现方法,结合 CSS 动画和动态样式绑定。
核心思路
- 使用 Vue 动态绑定样式,通过
v-bind:style控制颜色和动画。 - 通过 CSS
@keyframes定义颜色循环变化的动画。 - 使用 Vue 的
setInterval或 CSS 动画自动触发颜色切换。
方法 1:纯 CSS 动画 + Vue 模板
通过 CSS 动画实现颜色循环,Vue 仅负责渲染结构和类名绑定。
<template>
<div class="barber-light"></div>
</template>
<style>
.barber-light {
width: 200px;
height: 50px;
background: linear-gradient(90deg,
red, orange, yellow, green, blue, purple);
background-size: 600% 100%;
animation: barberEffect 3s linear infinite;
}
@keyframes barberEffect {
0% { background-position: 0% 50%; }
100% { background-position: 100% 50%; }
}
</style>
说明:
background-size: 600%扩展背景尺寸,实现颜色拉伸。animation通过background-position的移动实现颜色流动效果。
方法 2:Vue 动态样式绑定
通过 Vue 的响应式数据动态修改样式,适合更复杂的交互逻辑。
<template>
<div
class="barber-light"
:style="{ background: gradientStyle }"
></div>
</template>
<script>
export default {
data() {
return {
colors: ['red', 'orange', 'yellow', 'green', 'blue', 'purple'],
currentIndex: 0
};
},
computed: {
gradientStyle() {
const color1 = this.colors[this.currentIndex];
const color2 = this.colors[(this.currentIndex + 1) % this.colors.length];
return `linear-gradient(90deg, ${color1}, ${color2})`;
}
},
mounted() {
setInterval(() => {
this.currentIndex = (this.currentIndex + 1) % this.colors.length;
}, 500);
}
};
</script>
<style>
.barber-light {
width: 200px;
height: 50px;
transition: background 0.5s ease;
}
</style>
说明:
colors数组定义循环的颜色序列。setInterval每 500ms 切换颜色索引,通过计算属性生成渐变色。
方法 3:结合 SVG 和 Vue
使用 SVG 实现更复杂的灯光效果,Vue 控制动态属性。
<template>
<svg width="200" height="50">
<defs>
<linearGradient id="barberGradient" x1="0%" y1="0%" x2="100%" y2="0%">
<stop
v-for="(color, index) in colors"
:key="index"
:offset="`${(index / (colors.length - 1)) * 100}%`"
:stop-color="color"
/>
</linearGradient>
</defs>
<rect
width="100%"
height="100%"
fill="url(#barberGradient)"
:style="{ filter: 'blur(2px)' }"
/>
</svg>
</template>
<script>
export default {
data() {
return {
colors: ['red', 'orange', 'yellow', 'green', 'blue', 'purple']
};
}
};
</script>
说明:
- SVG 的
linearGradient实现平滑颜色过渡。 v-for动态生成渐变色的色标(stop)。
注意事项
- 性能优化:CSS 动画性能优于 JavaScript 驱动的样式修改。
- 兼容性:渐变效果在旧浏览器中可能需要前缀(如
-webkit-)。 - 扩展性:可通过 Vue 的
props接收颜色列表或动画时长参数。







