vue3-watermark-plugin
v1.0.2
Published
A powerful Vue 3 watermark plugin with component and directive support
Maintainers
Readme
Vue3 Watermark Plugin
一个功能完整的 Vue 3 水印插件,支持指令和组件两种使用方式。
功能特性
- ✅ 支持自定义文本内容
- ✅ 支持字体大小设置
- ✅ 支持字体颜色设置
- ✅ 支持字体加粗
- ✅ 支持旋转角度设置
- ✅ 支持横向和纵向间距设置
- ✅ 防篡改保护(自动重新生成被删除的水印)
- ✅ 响应式更新
- ✅ TypeScript 支持
- ✅ 轻量级,无外部依赖
安装
npm install vue3-watermark-plugin快速开始
1. 注册插件
import { createApp } from "vue";
import App from "./App.vue";
import WatermarkPlugin from "vue3-watermark-plugin";
const app = createApp(App);
app.use(WatermarkPlugin);
app.mount("#app");2. 按需引入
import { WatermarkComponent, watermarkDirective } from "vue3-watermark-plugin";
// 注册组件
app.component("Watermark", WatermarkComponent);
// 注册指令
app.directive("watermark", watermarkDirective);使用方式
指令形式(推荐)
<template>
<!-- 基础使用 -->
<div v-watermark="{ content: '机密文档' }">内容区域</div>
<!-- 完整配置 -->
<div v-watermark="watermarkConfig">内容区域</div>
</template>
<script setup>
import { reactive } from "vue";
const watermarkConfig = reactive({
content: "机密文档", // 水印文本
fontSize: 16, // 字体大小
color: "rgba(255, 0, 0, 0.2)", // 字体颜色
bold: false, // 是否加粗
rotate: -20, // 旋转角度
gapX: 120, // 横向间距
gapY: 80, // 纵向间距
});
</script>组件形式
<template>
<Watermark
content="内部资料"
:fontSize="18"
color="rgba(0, 0, 255, 0.15)"
:bold="true"
:rotate="15"
:gapX="100"
:gapY="100"
:visible="showWatermark"
>
<div class="content">这里是需要添加水印的内容</div>
</Watermark>
</template>
<script setup>
import { ref } from "vue";
import Watermark from "@/components/Watermark/index.vue";
const showWatermark = ref(true);
</script>配置参数
| 参数 | 类型 | 默认值 | 说明 | | -------- | ------- | --------------------- | -------------------------------------- | | content | String | '水印文本' | 水印显示的文本内容 | | fontSize | Number | 16 | 字体大小(px) | | color | String | 'rgba(0, 0, 0, 0.15)' | 字体颜色,支持任何 CSS 颜色值 | | bold | Boolean | false | 是否加粗字体 | | rotate | Number | -20 | 旋转角度(度),正数顺时针,负数逆时针 | | gapX | Number | 100 | 水印之间的横向间距(px) | | gapY | Number | 100 | 水印之间的纵向间距(px) | | zIndex | Number | 9999 | 水印层级 | | visible | Boolean | true | 是否显示水印(仅组件形式支持) |
高级用法
动态更新水印
<template>
<div>
<button @click="updateWatermark">更新水印</button>
<div v-watermark="config" class="content">内容区域</div>
</div>
</template>
<script setup>
import { ref } from "vue";
const config = ref({
content: "初始水印",
fontSize: 16,
color: "rgba(0, 0, 0, 0.15)",
});
const updateWatermark = () => {
config.value = {
content: "更新后的水印",
fontSize: 20,
color: "rgba(255, 0, 0, 0.3)",
};
};
</script>条件显示水印
<template>
<div v-watermark="showWatermark ? watermarkConfig : null">内容区域</div>
</template>
<script setup>
import { ref, computed } from "vue";
const showWatermark = ref(true);
const watermarkConfig = computed(() =>
showWatermark.value
? {
content: "机密文档",
fontSize: 16,
}
: null
);
</script>注意事项
- 性能优化:水印使用 Canvas 生成,大量使用时注意性能
- 防篡改:插件内置防篡改机制,但不能防止禁用 JavaScript
- 样式冲突:确保容器元素有适当的定位(relative/absolute/fixed)
- 响应式:水印会自动适应容器大小变化
浏览器兼容性
- Chrome 60+
- Firefox 55+
- Safari 12+
- Edge 79+
示例
查看 demo.vue 文件获取完整的使用示例。
