vue3中封装全局水印指令——加水印(使用篇)

今天看到公司老师封装的指令,觉得有必要学习下。一起来看吧。我只是把老师的知识留存一份,看到应该高兴吧,哈哈

第一:vue3项目中新建directive文件夹,在directive文件下新建waterMarker文件夹–index.ts文件。
如图
在这里插入图片描述
第二:waterMarker文件夹下的index.ts-指令主题部分

/**
 * v-waterMarker可接收参数,均为非必填
 * { text: 'vue-admin-box', font: '16px Microsoft JhengHei', textColor: '#000' }
 */
import {
    
     Color, FontFamilyProperty, FontProperty } from 'csstype'
import type {
    
     Directive, DirectiveBinding } from 'vue'

const directive: Directive = {
    
    
//el: HTMLElement,绑定的父级DOM//     binding: DirectiveBinding//指令传来的参数对象
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    
    
    binding.value ? binding.value : binding.value = {
    
    }
    addWaterMarker(binding.value.text, el, binding.value.font, binding.value.textColor, )
  },
}

function addWaterMarker(str: string, parentNode: HTMLElement, font: FontProperty, textColor: Color) {
    
    
  // 水印文字,父元素,字体,文字颜色
  var can = document.createElement('canvas') as HTMLCanvasElement
  parentNode.appendChild(can)
  can.width = 200
  can.height = 150
  can.style.display = 'none'
  var cans = can.getContext('2d') as CanvasRenderingContext2D
  cans.rotate((-20 * Math.PI) / 180)
  cans.font = font || '16px Microsoft JhengHei'
  cans.fillStyle = textColor || 'rgba(180, 180, 180, 0.3)'
  cans.textAlign = 'left'
  cans.textBaseline = 'middle'
  cans.fillText(str ||'vue-admin-box' , can.width / 10, can.height / 2)
  parentNode.style.backgroundImage = 'url(' + can.toDataURL('image/png') + ')'
}

export default directive

第三:在directive下的index.ts文件中把指令主题引入(所有指令汇总到此文件夹,便于维护管理)
代码:

import waterMarker from "./waterMarker";
const directivesList: any = {
    
    
    // 这里放指令
    waterMarker,//水印指令
};
const directives = {
    
    
    install: function (app: App<Element>) {
    
    
        Object.keys(directivesList).forEach(key => {
    
    
            // 注册自定义指令
            app.directive(key, directivesList[key]);
        });
    }
};
 
export default directives;

第四:第三部的文件在main.ts全局引入,这里main.ts只针对水印指令

// An highlighted block
import App from './App.vue'
import directives from './directive'
const app = createApp(App)
app.use(directives)
app.config.performance = true
app.mount('#app')

最后 使用:

// text为水印内容,textColor水印内容颜色
<div class="box" v-waterMarker="{text: 'Watermark Direct',textColor: 'rgba(180, 180, 180, 0.6)'}">水印指令</div>

以上就是指令内容,下一篇(应用篇)将解决一些实际场景。

猜你喜欢

转载自blog.csdn.net/qq_48850466/article/details/127761136
今日推荐