vue实现点击涟漪
在Vue中实现点击涟漪效果可以通过多种方式完成,以下是常见的几种方法:
使用Vuetify内置组件
Vuetify提供了现成的v-ripple指令,可直接为元素添加涟漪效果。安装Vuetify后,在模板中使用:
<template>
<v-btn v-ripple>点击触发涟漪</v-btn>
</template>
自定义CSS实现
通过动态添加CSS类实现涟漪动画效果:
<template>
<div class="ripple-container" @click="createRipple">
<span class="ripple" :class="{ active: isRippling }"></span>
<slot></slot>
</div>
</template>
<script>
export default {
data() {
return { isRippling: false }
},
methods: {
createRipple(e) {
this.isRippling = true
setTimeout(() => this.isRippling = false, 600)
}
}
}
</script>
<style>
.ripple-container {
position: relative;
overflow: hidden;
}
.ripple {
position: absolute;
border-radius: 50%;
transform: scale(0);
animation: ripple 0.6s linear;
background-color: rgba(255, 255, 255, 0.7);
}
.ripple.active {
animation: ripple 0.6s linear;
}
@keyframes ripple {
to {
transform: scale(4);
opacity: 0;
}
}
</style>
使用第三方库
安装vue-ripple-directive库:
npm install vue-ripple-directive
在项目中注册指令后使用:
import VueRipple from 'vue-ripple-directive'
Vue.directive('ripple', VueRipple)
<button v-ripple>点击触发涟漪</button>
动态计算涟漪位置
通过JavaScript计算点击位置实现精确定位:
<template>
<div class="ripple-parent" @click="handleClick">
<div
v-if="showRipple"
class="ripple-effect"
:style="rippleStyle"
></div>
<slot></slot>
</div>
</template>
<script>
export default {
data() {
return {
showRipple: false,
rippleStyle: {}
}
},
methods: {
handleClick(e) {
const rect = e.target.getBoundingClientRect()
this.rippleStyle = {
left: `${e.clientX - rect.left}px`,
top: `${e.clientY - rect.top}px`
}
this.showRipple = true
setTimeout(() => this.showRipple = false, 600)
}
}
}
</script>
<style>
.ripple-parent {
position: relative;
overflow: hidden;
}
.ripple-effect {
position: absolute;
width: 100px;
height: 100px;
background: rgba(0, 0, 0, 0.1);
border-radius: 50%;
transform: translate(-50%, -50%) scale(0);
animation: ripple 0.6s ease-out;
}
@keyframes ripple {
to {
transform: translate(-50%, -50%) scale(3);
opacity: 0;
}
}
</style>
每种方法各有特点:Vuetify方案最便捷但需引入整个UI库;CSS方案轻量但需要手动处理动画逻辑;第三方库方案平衡了易用性和体积;动态计算方案实现最精细的定位效果。可根据项目需求选择合适方案。







