原理:利用MutationObserver监听父节点的子节点变化,如果变化,重新创建水印节点并添加到父节点中
代码如下:
父节点中一开始要有我们的水印节点,然后在mounted中执行我们的waterMarkBgObserver,切记在beforeDestory中销毁waterMarkBgObserver,销毁方法:this.moObserver.disconnect()
createWaterMark(){var parent = document.querySelector('#imageDom')var waterMarkBg = document.createElement('view')waterMarkBg.className = 'waterMarkBg'waterMarkBg.style.width = '100%'waterMarkBg.style.height = '100%'waterMarkBg.style.position = 'absolute'waterMarkBg.style.backgroundImage = `url(${this.watermarkUrl})`waterMarkBg.style.top = '0'waterMarkBg.style.right = '0'waterMarkBg.style.backgroundSize = '140px 140px'waterMarkBg.style.zIndex = '-1'parent.appendChild(waterMarkBg)},//水印监听器waterMarkBgObserver(){this.moObserver = new MutationObserver(()=>{var waterMarkBgDom = document.querySelector('.waterMarkBg')if(!waterMarkBgDom){this.createWaterMark()}})let config = { attributes: true,subtree: true,childList: true };this.moObserver.observe(document.querySelector('#imageDom'),config)},