wangeditor富文本实现编辑器复制粘贴外部图文和查看源码功能

1,675 阅读1分钟

一、需求说明

复制外部的图文内容到wangeditor富文本中和为富文本添加查看源码功能,但是复制的图片链接是网上的链接可能涉及侵权,需要将线上图片链接转化成自己的链接。

二、需求分析

通过查看wangeditor文档,发现W(wangeditor自我定义的简称)可以通过使用 editor.txt.getJSON() 获取 JSON 格式的内容,JSON格式如下:

[{
	"tag": "p",
	"attrs": [{
		"name": "style",
		"value": "margin-right: auto; margin-left: auto; color: rgb(73, 73, 73); font-family: 微软雅黑, 宋体, Arial; font-size: 14px;"
	}],
	"children": [{
		"tag": "img",
		"attrs": [{
			"name": "src",
			"value": "https://img2018.cnblogs.com/blog/1319943/201903/1319943-20190306164156836-740890134.png"
		}, {
			"name": "alt",
			"value": ""
		}, {
			"name": "style",
			"value": "border-width: 0px; border-style: initial; max-width: 100%; cursor: zoom-in; height: auto; transition: transform 0.3s cubic-bezier(0.2, 0, 0.2, 1) 0s !important;"
		}],
		"children": []
	}]
}, {
	"tag": "p",
	"attrs": [{
		"name": "style",
		"value": "margin-right: auto; margin-left: auto; color: rgb(73, 73, 73); font-family: 微软雅黑, 宋体, Arial; font-size: 14px;"
	}],
	"children": ["容器"]
}, {
	"tag": "p",
	"attrs": [{
		"name": "style",
		"value": "margin-right: auto; margin-left: auto; color: rgb(73, 73, 73); font-family: 微软雅黑, 宋体, Arial; font-size: 14px;"
	}],
	"children": ["主要分为三大部分  最外层box      工具栏box  内容区box"]
}]

这样就可以通过遍历JSON格式内容找到属性值name为src即为线上图片链接,并传给后端然后后端返回新的图片链接在通过遍历JSON将图片链接替换之后通过editor.txt.setJSON()可设置内容。

后端返回JSON数据如下(也可以和后端协商其他返回结果):

[{
	"source": "https://img.alicdn.com/bao/uploaded/i3/2103587316/O1CN01aPeOoq23umKvToUbz_!!2103587316.jpg_180x180.jpg",
	"url": "https://img5.912688.com/27dbd79d336f4e0e869b1073628468e2.png"
}, {
	"source": "https://img.alicdn.com/bao/uploaded/i1/2103587316/O1CN01v3UFdN23umHSilNNH_!!2103587316.jpg_180x180.jpg",
	"url": "https://img5.912688.com/fca14c47950c4eb59218d3629449ddbd.png"
}, {
	"source": "https://img.alicdn.com/bao/uploaded/i1/2103587316/O1CN01qf7Ukc23umAjixas3_!!2103587316.jpg_180x180.jpg",
	"url": "https://img6.912688.com/9bd47945708e435bbc0ad7bbe299aa10.png"
}, {
	"source": "https://img.alicdn.com/bao/uploaded/i4/2103587316/O1CN01b2eqkF23umCwB8Gc5_!!2103587316.jpg_180x180.jpg",
	"url": "https://img4.912688.com/e8810895abca4bc1a750fc8c9cecddee.png"
}]

参数说明 source:线上链接;

url:自己的链接。

三、代码实现

<template>
  <div class="rightext">
    <div id="editor" class="editor"></div>
    <div class="img1">
      <imgControl
        :origin="origin"
        @child-event="fiveclick"
        :styles="btn"
        v-if="!one"
      ></imgControl>
    </div>
    <p class="htmlShift" @click="htmlShift">HTML</p>
  </div>
</template>

<script>
// import E from "wangeditor";
export default {
  data() {
    return {
      editor: "",
      isHTML:true,
      wb: "",
      pasteChange:false,
      arr:[],
      pasteArr:[],
      //模拟后端返货JSON数据
      attrArr: [
      {
      "source": "https://img.alicdn.com/bao/uploaded/i3/2103587316/O1CN01aPeOoq23umKvToUbz_!!2103587316.jpg_180x180.jpg","url": "https://img5.912688.com/27dbd79d336f4e0e869b1073628468e2.png"},{"source": "https://img.alicdn.com/bao/uploaded/i1/2103587316/O1CN01v3UFdN23umHSilNNH_!!2103587316.jpg_180x180.jpg","url": "https://img5.912688.com/fca14c47950c4eb59218d3629449ddbd.png"},{"source": "https://img.alicdn.com/bao/uploaded/i1/2103587316/O1CN01qf7Ukc23umAjixas3_!!2103587316.jpg_180x180.jpg","url": "https://img6.912688.com/9bd47945708e435bbc0ad7bbe299aa10.png"},{"source": "https://img.alicdn.com/bao/uploaded/i4/2103587316/O1CN01b2eqkF23umCwB8Gc5_!!2103587316.jpg_180x180.jpg","url": "https://img4.912688.com/e8810895abca4bc1a750fc8c9cecddee.png"} ]
    };
  },
  created() {
  
  },
  mounted() {
    const E = window.wangEditor
    this.editor = new E("#editor");
    var that = this;
    //复制文本到编辑器中,编辑器会默认过滤掉复制文本的样式,可通过设置 editor.config.pasteFilterStyle = false 来关闭样式过滤。
    this.editor.config.pasteFilterStyle = false
    //对粘贴的文本内容进行自定义的过滤、处理等操作
    this.editor.config.pasteTextHandle = function (pasteStr) {
        that.pasteChange = true;//判断是不是复制文本到编辑器中
        return pasteStr;
    }
    this.editor.config.onchange = (text) => {
        this.arr = [];
        this.pasteArr = [];
      if (this.pasteChange) {
        this.pasteArr = this.getImg(that.editor.txt.getJSON());
        this.pasteChange = false;
      }
      //输入html
      console.log(this.editor.txt.html(),'html')//输入html
      // this.wb=this.editor.txt.text()//文本
      this.wb = this.setImg(that.editor.txt.getJSON(),this.attrArr);
      //向子元素传递内容
      this.$emit("childByValue", this.wb,this.editor.txt.text());
    };
    //编辑器删除事件
    this.editor.txt.eventHooks.deleteUpEvents.push(this.emptyData);
    //设置编辑器菜单
    this.editor.config.menus = [
      "table", //表格
      // 'fontName',//字体
      "fontSize", //字体大小
      "foreColor", //字体颜色
      "backColor", //文字背景色
      "bold", //字体加粗
      "italic", //斜体
      "underline", //下划线
      "justify", //对齐方式
      "indent", //首行缩进
      // 'image',图片
      "list", //有序列表、无序列表
    ];
    // function img(editor){
    //   var _this=this

    // }
    this.editor.create();
  },
  methods: {
    //编辑器删除
    emptyData(){
      if (this.editor.txt.text() == "") {
          // this.editor.txt.html('');
          this.editor.txt.clear()
      }
    },
    //源码切换
    htmlShift(){
      let source;
      if (this.isHTML) {
          source = this.editor.txt.html().replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/ /g, "&nbsp;");
          this.isHTML = false;
      } else {
        source = this.editor.txt.text().replace(/&lt;/ig, "<").replace(/&gt;/ig, ">").replace(/&nbsp;/ig, " ");
        this.isHTML = true;
      }
      this.editor.txt.html(source)
    },
    //获取粘贴内容包含图片的链接
    getImg(data){
      data.forEach(element => {
        // console.log(element);
        if (element.attrs) {
          element.attrs.forEach(element => {
            if (element.name == "src") {
              this.arr.push(element.value)
            }
          });
          this.getImg(element.children);
        }
      });
      return this.arr;
    },
    //将获取粘贴内容包含图片的链接替换为自己的图片链接
    setImg(jsonData,arrt){
      jsonData.forEach(element => {
          // console.log(element);
          if (element.attrs) {
            element.attrs.forEach(element => {
              if (element.name == "src") {
                arrt.forEach(item => {
                  if (element.value == item.source) {
                    element.value = item.url
                  }
                });
              }
              if (element.name == "href") {
                element.value = "javascript:void(0);"
                element.name = "xx-href";
              }
            });
            this.setImg(element.children,arrt);
          }
        });
      return this.editor.txt.setJSON(jsonData);
    }
  },
};
</script>

<style lang="stylus" scoped>
.rightext {
  position: relative;
  .htmlShift{
    position: absolute;
    top: 5px;
    left: 455px;
    font-size 12px;
    cursor: pointer;
  }
  .editor {
    width: 100%;
    margin: 0 auto;
    position: relative;
    z-index: 0;
    >>>.w-e-text-container{
      height:auto !important;
      min-height: 300px;
    }
    >>>.w-e-toolbar .w-e-menu:last-child {
      display: none;
    }
  }
}
</style>