Vue之全局水印的實現示例

【需求】系統內頁面顯示水印,登錄頁面沒有水印(退出登錄時,登錄頁面不會顯示水印)

1.創建水印Js文件

/*
 * @Author: 劉小二
 * @Date: 2021-07-15 14:43:27
 * @LastEditTime: 2021-07-15 15:00:27
 * @LastEditors: Please set LastEditors
 * @Description: 添加水印
 * @FilePath: /huashijc_MeetingSys/src/common/warterMark.js
 */
'use strict'
 
let watermark = {}
 
let setWatermark = (str) => {
  let id = '1.23452384164.123412415'
 
  if (document.getElementById(id) !== null) {
    document.body.removeChild(document.getElementById(id))
  }
 
  let can = document.createElement('canvas')
  can.width = 250
  can.height = 120
 
  let cans = can.getContext('2d')
  cans.rotate(-15 * Math.PI / 150)
  cans.font = '20px Vedana'
  cans.fillStyle = 'rgba(200, 200, 200, 0.20)'
  cans.textAlign = 'left'
  cans.textBaseline = 'Middle'
  cans.fillText(str, can.width / 8, can.height / 2)
 
  let div = document.createElement('div')
  div.id = id
  div.style.pointerEvents = 'none'
  div.style.top = '35px'
  div.style.left = '0px'
  div.style.position = 'fixed'
  div.style.zIndex = '100000'
  div.style.width = document.documentElement.clientWidth + 'px'
  div.style.height = document.documentElement.clientHeight + 'px'
  div.style.background = 'url(' + can.toDataURL('image/png') + ') left top repeat'
  document.body.appendChild(div)
  return id
}
 
// 該方法隻允許調用一次
watermark.set = (str) => {
  let id = setWatermark(str)
  setInterval(() => {
    if (document.getElementById(id) === null) {
      id = setWatermark(str)
    }
  }, 500)
  window.onresize = () => {
    setWatermark(str)
  }
}

const outWatermark = (id) => {
    if (document.getElementById(id) !== null) {
      const div = document.getElementById(id)
      div.style.display = 'none'
    }
}
watermark.out = () => {
    const str = '1.23452384164.123412415'
    outWatermark(str)
}
 
export default watermark

2.引入操作

2.1 在App.vue中引用或其他頁面

// 1.在App.vue文件中,導入該文件
import Watemark from '@/common/watermark';

computed: {
  userName() {
    const name = this.$store.state.user.name
    return (name && name.length > 0) ? name : '未獲取到用戶名'
  }
},
mounted() {
  Watermark.set(this.userName)
}

// 2.在其他頁面引用
import Watemark from '@/common/watermark';

created() {
  Watermark.set('admin')
}

2.2 在router配置文件中引用

const outWatermark = (id) => {
  if (document.getElementById(id) !== null) {
    const div = document.getElementById(id)
    div.style.display = 'none'
  }
}

router.afterEach((to) => {
 if(to.path == '/'){
  Watermark.out() // 清除水印
 }else{
  Watermark.set('未獲取到用戶名') // 設置水印title
 }
});

到此這篇關於Vue之全局水印的實現示例的文章就介紹到這瞭,更多相關Vue 全局水印內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: