基于vue3-signature封装电子签名组件(复制即可使用)
下载插件
npm install vue3-signature --save-dev
全局注入
在main.ts文件中
import { createApp } from "vue";
import App from "./App.vue";
import Vue3Signature from "vue3-signature";
import "vant/es/toast/style";
const app = createApp(App);
app.use(Vue3Signature).mount("#app");
封装组件
components/signature/index.ts
<template>
<div class="signature">
<Vue3Signature
ref="signature"
:sigOption="state.option"
:h="props.height"
:disabled="props.disabled"
class="canvas"
/>
<van-space class="action" v-if="!props.disabled">
<van-button size="small" @click="undo">撤销</van-button>
<van-button size="small" @click="clear">清除</van-button>
<van-button type="primary" size="small" @click="save(props.imageType)"
>保存</van-button
>
</van-space>
</div>
</template>
<script setup lang="ts">
import { reactive, ref } from "vue";
/**
* 参数名 类型 描述
* height String 画布高度
* imageType String 图片类型
* disabled Boolean 是否禁用画布
*/
const props = defineProps({
height: {
type: String,
default: "11.25rem"
},
imageType: {
type: String,
default: "image/png"
},
disabled: {
type: Boolean,
default: false
}
});
const emit = defineEmits(["image-value"]);
const state = reactive({
option: {
penColor: "rgb(0, 0, 0)",
backgroundColor: "rgb(255,255,255)"
}
});
const signature = ref();
const save = (t: any) => {
emit("image-value", signature.value.save(t), "save");
};
const clear = () => {
signature.value.clear();
emit("image-value", "", "clear");
};
const undo = () => {
signature.value.undo();
};
const isEmpty = () => {
return signature.value.isEmpty();
};
defineExpose({
isEmpty
});
</script>
<style lang="less" scoped>
.signature {
margin: 0.75rem;
.canvas {
border: 0.0625rem dotted #ccc;
}
.action {
margin: 0.75rem 0;
float: right;
}
}
</style>
父组件引用
<template>
<signature ref="canvas" @image-value="getImageValue" />
</template>
<script setup lang="ts">
import { ref, defineAsyncComponent } from "vue";
import { showFailToast } from "vant";
const signature = defineAsyncComponent(
() => import("@/components/Signature/index.vue")
);
const canvas = ref();
const getImageValue = (value: string, type: string) => {
if (canvas.value.isEmpty() && type === "save") {
return showFailToast("请先签名");
} else {
console.log(value, "---签名输出的image值---");
}
};
</script>
实现效果
画布为空时:
画布不为空时: