Vue2+wangEditor5 rich text editor (picture video upload) and add anchor link

1. Use of wangEditor text editor

Official website: https://www.wangeditor.com/v5/installation.html#npm

1. Installation and use

Install

yarn add @wangeditor/editor
# 或者 npm install @wangeditor/editor --save
yarn add @wangeditor/editor-for-vue
# 或者 npm install @wangeditor/editor-for-vue --save

Introduce styles in main.js

import '@wangeditor/editor/dist/css/style.css'

Introduce js in the page using the editor

import {
    
     Editor, Toolbar } from "@wangeditor/editor-for-vue";
components: {
    
     Editor, Toolbar },

template

<template>
  <div>
    <div style="border: 1px solid #ccc; margin-top: 10px">
      <!-- 工具栏 -->
      <Toolbar
        style="border-bottom: 1px solid #ccc"
        :editor="editor"
        :defaultConfig="toolbarConfig"
      />
      <!-- 编辑器 -->
      <Editor
        style="height: 400px; overflow-y: hidden"
        :defaultConfig="editorConfig"
        v-model="html"
        @onChange="onChange"
        @onCreated="onCreated"
      />
    </div>
  </div>
</template>

js

<script>
import {
    
     Editor, Toolbar } from "@wangeditor/editor-for-vue";
export default {
    
    
  name: "MyEditor",
  components: {
    
     Editor, Toolbar },
  data() {
    
    
    return {
    
    
      editor: null,
      html: "<p>hello&nbsp;world</p>",
      toolbarConfig: {
    
    },
      editorConfig: {
    
    
        placeholder: "请输入内容...",
        // 所有的菜单配置,都要在 MENU_CONF 属性下
        MENU_CONF: {
    
    },
      },
    };
  },
  methods: {
    
    
    onCreated(editor) {
    
    
      this.editor = Object.seal(editor); // 【注意】一定要用 Object.seal() 否则会报错
    },
    onChange(editor) {
    
    
      console.log("onChange", editor.getHtml()); // onChange 时获取编辑器最新内容
    },
  },
  mounted() {
    
    },
  beforeDestroy() {
    
    
    const editor = this.editor;
    if (editor == null) return;
    editor.destroy(); // 组件销毁时,及时销毁 editor ,重要!!!
  },
};
</script>

After editing at this step, it can be displayed normally

insert image description here

2. Upload pictures and videos

1) Uploading to the background interface can be done directly according to the configuration of the document. The return format of the interface should also be consistent with the document. 2
insert image description here
) Custom upload (usually uploaded to other servers, mine is uploaded to Qiniu cloud server)
in data configuration upload pictures and videos

editorConfig: {
    
    
        placeholder: "请输入内容...",
        // 所有的菜单配置,都要在 MENU_CONF 属性下
        MENU_CONF: {
    
    
          uploadImage: {
    
    
            customUpload: async (file, insertFn) => {
    
    
              let resultUrl = await this.upqiniu(file, file.name);
              insertFn(resultUrl);
            },
          },
          uploadVideo: {
    
    
            customUpload: async (file, insertFn) => {
    
    
              let resultUrl = await this.upqiniu(file, file.name);
              insertFn(resultUrl);
            },
          },
        },
      },

this.upqiniu is the code I wrote to upload the server, and finally just return the address returned by the interface.

 upqiniu(file, name) {
    
    
      return new Promise((resolve) => {
    
    
        let config = {
    
    
          useCdnDomain: true, //表示是否使用 cdn 加速域名,为布尔值,true 表示使用,默认为 false。
          region: null, // 根据具体提示修改上传地区,当为 null 或 undefined 时,自动分析上传域名区域
        };
        let putExtra = {
    
    
          fname: `upload_pic_${
      
      name}`, //文件原文件名
          params: {
    
    }, //用来放置自定义变量
          mimeType: null, //用来限制上传文件类型,为 null 时表示不对文件类型限制;限制类型放到数组里: ["image/png", "image/jpeg", "image/gif"]
        };
        var observable = qiniu.upload(
          file,
          `upload_pic_${
      
      name}`,
          this.token,
          putExtra,
          config
        );
        observable.subscribe({
    
    
          next: (result) => {
    
    
            // 主要用来展示进度
          },
          error: (errResult) => {
    
    
            // 失败报错信息
          },
          complete: (result) => {
    
    
            // 接收成功后返回的信息
            let url = "http://image.gewu.pro/" + result.key;
            resolve(url);
          },
        });
      });
    },

2. Add anchor link

The requirement is that when editing in a rich text editor, the title can be displayed on the left, and after editing, click the title on the left to jump to the corresponding title position. Here I use the anchor link to achieve

insert image description here
insert image description here

1. In the onchange event of the edit box, bring out the tags with h1-h2 and add anchor links

 onChange() {
    
    
      let reg = /<h[1-6][\s\S]*?h[1-6]>/g;
      this.hArr = this.html.match(reg);//所有的h标签
      this.titleArr = [];//添加锚链接的标题
      if (this.hArr) {
    
    
        this.hArr.forEach((item, i) => {
    
    
          // 标题
          let text = item.replace(/<[^>]+>/g, "");
          this.titleArr.push(`<a href="#miao${
      
      i}">${
      
      text}</a>`);
        });
      }
    },

2. Add id to the title of the article when saving in the editor

 		let zhengwen = JSON.parse(JSON.stringify(this.html));
          if (this.hArr) {
    
    
            this.hArr.forEach((item, i) => {
    
    
              // 替换文章标签
              let itemArr = item.split("");
              itemArr.splice(3, 0, ` id="miao${
      
      i}"`);
              let xinItem = itemArr.join("");
              zhengwen = zhengwen.replace(item, xinItem);
            });
          }
  // 最后将zhengwen (编辑器的文章内容)和 titleArr 单独传给接口查看的时候就能实现锚链接的功能

insert image description here

Guess you like

Origin blog.csdn.net/qq_44854653/article/details/126524523