首页 > 解决方案 > 如何在可编辑组件(vue)中的复制/粘贴操作中过滤文本内容

问题描述

我已经实现了一个组件,它使用 contenteditable="true" 来获得在这个 div 上编辑内容的可能性(如 textarea)。

按照我的代码片段:

export default {
  name: 'divArea',
  props: ['value'],
  mounted() {
    this.$el.innerHTML = this.value;
  },
  methods: {
    updateHTML(e) {
      const html = e.target.innerHTML;
      this.$emit('input', html);
    },
  },
}
<template>
  <div contenteditable="true"
    v-once
    v-html="value"
    @input="updateHTML"
    @paste="onPaste"
    class="txtArea"></div>
</template>

我正在尝试在此区域中实现粘贴功能以从 html 页面复制内容块,但我希望在粘贴操作后只有文本版本(无 html)。

目前我在我的组件上使用 v-html 属性和一个道具,因为我需要在粘贴的文本上添加一个 html 自定义标签,但前提是用户单击一个按钮。

我该怎么做才能实现这种行为?

标签: javascriptvue.jsvuejs2

解决方案


首先contenteditable是一个真正的恶魔,我建议不要使用它,但无论如何这是我的解决方案

        let contenteditable = document.querySelector('[contenteditable]')
        contenteditable.addEventListener('paste', function(e){           
            // Prevent the default pasting event and stop bubbling            
            e.preventDefault()
            e.stopPropagation()
            // Get the clipboard data
            let paste = (e.clipboardData || window.clipboardData).getData('text/plain')

            // Do something with paste like remove non-UTF-8 characters            
            paste = paste.replace(/\x0D/gi, "\n")          
            e.target.textContent += paste
        })

第二部分,如果你想在原处添加cursor粘贴

  instead of 
            e.target.textContent += paste

您可以使用Selection()

       // Find the cursor location or highlighted area
        const selection = window.getSelection()
        // Cancel the paste operation if the cursor or highlighted area isn't found
        // if (!selection.rangeCount) return false
        // Paste the modified clipboard content where it was intended to go            
        if(selection.getRangeAt(0).collapsed){
            // TextareaManager.AddToCursor(document.createTextNode(paste))
            if(selection.getRangeAt(0).endContainer.nodeName != "DIV"){
                selection.getRangeAt(0).insertNode(document.createTextNode(paste))
            }else {
                e.target.childNodes[0].textContent += paste
            }
            selection.getRangeAt(0).collapse(false)
        }else {
           e.target.appendChild(document.createTextNode(paste))
        }

推荐阅读