vue实现点亮灯光
Vue 实现点亮灯光效果
使用 Vue 实现点亮灯光效果可以通过动态绑定样式或类名,结合 CSS 动画或过渡效果完成。以下是几种常见实现方式:
动态类名绑定
通过 v-bind:class 动态切换类名,控制灯光亮灭状态:
<template>
<div>
<div class="light" :class="{ 'light-on': isOn }"></div>
<button @click="toggleLight">Toggle Light</button>
</div>
</template>
<script>
export default {
data() {
return {
isOn: false
}
},
methods: {
toggleLight() {
this.isOn = !this.isOn
}
}
}
</script>
<style>
.light {
width: 100px;
height: 100px;
border-radius: 50%;
background-color: #ccc;
transition: background-color 0.3s;
}
.light-on {
background-color: yellow;
box-shadow: 0 0 20px yellow;
}
</style>
使用 CSS 动画
添加更生动的发光动画效果:
.light-on {
background-color: yellow;
animation: glow 1s infinite alternate;
}
@keyframes glow {
from {
box-shadow: 0 0 10px yellow;
}
to {
box-shadow: 0 0 30px yellow;
}
}
多个灯光控制
控制多个灯光可以使用数组存储状态:
<template>
<div>
<div
v-for="(light, index) in lights"
:key="index"
class="light"
:class="{ 'light-on': light.isOn }"
@click="toggleLight(index)"
></div>
</div>
</template>
<script>
export default {
data() {
return {
lights: [
{ isOn: false },
{ isOn: false },
{ isOn: false }
]
}
},
methods: {
toggleLight(index) {
this.lights[index].isOn = !this.lights[index].isOn
}
}
}
</script>
使用第三方动画库
如需更复杂效果,可引入动画库如 anime.js 或 GSAP:
<template>
<div>
<div ref="light" class="light"></div>
<button @click="animateLight">Animate Light</button>
</div>
</template>
<script>
import anime from 'animejs'
export default {
methods: {
animateLight() {
anime({
targets: this.$refs.light,
backgroundColor: ['#ccc', 'yellow'],
boxShadow: ['0 0 0 rgba(255,255,0,0)', '0 0 20px yellow'],
duration: 1000,
easing: 'easeInOutQuad'
})
}
}
}
</script>
以上方法可根据实际需求选择或组合使用,Vue 的响应式特性使得状态管理和 DOM 更新变得简单高效。







