vue实现盖章组件
vue实现盖章组件的方法
实现一个盖章组件可以通过自定义指令或组件封装完成,以下是两种常见实现方式:
自定义指令实现
通过自定义指令v-stamp动态添加盖章效果:

Vue.directive('stamp', {
inserted(el, binding) {
const stamp = document.createElement('div')
stamp.className = 'vue-stamp'
stamp.innerHTML = binding.value || '已审核'
stamp.style = `
position: absolute;
transform: rotate(-15deg);
color: red;
font-size: 24px;
opacity: 0.8;
pointer-events: none;
user-select: none;
`
el.style.position = 'relative'
el.appendChild(stamp)
}
})
使用方式:
<div v-stamp="'通过审核'"></div>
组件化封装
创建可复用的Stamp组件:

<template>
<div class="stamp-container" :style="containerStyle">
<div class="stamp" :style="stampStyle">
{{ text }}
</div>
</div>
</template>
<script>
export default {
props: {
text: { type: String, default: '已盖章' },
color: { type: String, default: '#f00' },
size: { type: Number, default: 24 },
rotate: { type: Number, default: -15 },
opacity: { type: Number, default: 0.7 }
},
computed: {
stampStyle() {
return {
transform: `rotate(${this.rotate}deg)`,
color: this.color,
fontSize: `${this.size}px`,
opacity: this.opacity
}
},
containerStyle() {
return { position: 'relative' }
}
}
}
</script>
<style>
.stamp {
position: absolute;
pointer-events: none;
user-select: none;
z-index: 100;
}
</style>
动态位置控制
添加鼠标点击定位功能:
methods: {
handleClick(e) {
const stamp = this.$refs.stamp
stamp.style.left = `${e.offsetX - stamp.offsetWidth/2}px`
stamp.style.top = `${e.offsetY - stamp.offsetHeight/2}px`
}
}
高级效果实现
实现圆形印章效果:
<template>
<div class="seal" :style="sealStyle">
<div class="seal-circle"></div>
<div class="seal-text">{{ text }}</div>
</div>
</template>
<style>
.seal {
position: absolute;
width: 120px;
height: 120px;
border-radius: 50%;
border: 3px solid red;
display: flex;
justify-content: center;
align-items: center;
}
.seal-text {
transform: rotate(-15deg);
color: red;
font-weight: bold;
}
</style>
注意事项
- 需要设置
pointer-events: none避免遮挡交互 - 建议添加
z-index控制层级关系 - 动态定位时注意容器需设置
position: relative - 移动端需考虑触摸事件适配
以上实现可以根据实际需求组合使用,组件化方式更适合复杂场景和复用需求。






