vue实现点击涟漪
Vue 实现点击涟漪效果
在 Vue 中实现点击涟漪效果可以通过自定义指令或组件的方式完成。以下是两种常见实现方法:
使用自定义指令
创建一个自定义指令 v-ripple,动态生成涟漪元素并添加动画效果:
// 在 main.js 或单独指令文件中
Vue.directive('ripple', {
bind(el, binding) {
el.style.position = 'relative'
el.style.overflow = 'hidden'
el.addEventListener('click', (e) => {
const ripple = document.createElement('span')
ripple.className = 'ripple-effect'
const rect = el.getBoundingClientRect()
const size = Math.max(rect.width, rect.height)
const x = e.clientX - rect.left - size/2
const y = e.clientY - rect.top - size/2
ripple.style.width = ripple.style.height = `${size}px`
ripple.style.left = `${x}px`
ripple.style.top = `${y}px`
el.appendChild(ripple)
setTimeout(() => {
ripple.remove()
}, 600)
})
}
})
添加对应的 CSS 样式:
.ripple-effect {
position: absolute;
border-radius: 50%;
background-color: rgba(255, 255, 255, 0.7);
transform: scale(0);
animation: ripple 0.6s linear;
pointer-events: none;
}
@keyframes ripple {
to {
transform: scale(2);
opacity: 0;
}
}
使用组件方式
创建可复用的 Ripple 组件:
<template>
<div
class="ripple-container"
@click="createRipple"
ref="container"
>
<slot></slot>
<span
v-for="(ripple, index) in ripples"
:key="index"
class="ripple"
:style="{
left: ripple.x + 'px',
top: ripple.y + 'px',
width: ripple.size + 'px',
height: ripple.size + 'px'
}"
></span>
</div>
</template>
<script>
export default {
data() {
return {
ripples: []
}
},
methods: {
createRipple(e) {
const container = this.$refs.container
const rect = container.getBoundingClientRect()
const size = Math.max(rect.width, rect.height)
this.ripples.push({
x: e.clientX - rect.left - size/2,
y: e.clientY - rect.top - size/2,
size: size
})
setTimeout(() => {
this.ripples.shift()
}, 600)
}
}
}
</script>
<style scoped>
.ripple-container {
position: relative;
overflow: hidden;
display: inline-block;
}
.ripple {
position: absolute;
border-radius: 50%;
background-color: rgba(0, 0, 0, 0.1);
transform: scale(0);
animation: ripple 0.6s linear;
pointer-events: none;
}
@keyframes ripple {
to {
transform: scale(2);
opacity: 0;
}
}
</style>
使用第三方库
对于更复杂的需求,可以考虑使用现成的 Vue 涟漪效果库:
-
vue-ripple-directive:轻量级的涟漪指令npm install vue-ripple-directive -
vuetify:Material Design 组件库内置涟漪效果npm install vuetify
这些实现方法都可以根据项目需求调整涟漪颜色、大小和动画持续时间等参数。自定义指令方式适合快速添加基本效果,组件方式提供更好的封装性,而第三方库则提供最完整的解决方案。







