wangEditor在vue框架下的使用

178 阅读1分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 14 天、第 14 篇,点击查看活动详情

wangEditor是一个轻量级的微博富文本编辑器,在我最近的一个小项目中,与偶遇到部份内容在后台的编辑,需要使用富文本,但是第一次使用富文本编辑器的组件就踩了很多坑

首先这个项目的后台的基本框架是使用ruoyi自动生成的,ruoyi有自己封装好的富文本编辑器组件,这个组件功能也比较完善,只是他插入图片的功能是将图片转化为base64直接插入到文本内,这就导致文本会变得非常的大以至于无法直接插入到我们的数据库里,然后就使用了另外的组件,最终选定的就是wangEditor。

他有较完善的官方文档供我们阅读,上手比较简单,而且也会教你如何在vue框架中使用他的组件

首先在我们的项目中安装组件

npm 安装 npm i wangeditor –save

wangEditor``是用``TypeScript``开发的组件,我们使用的是vue框架,所以我们还需要在项目各根目录新建一个``tsconfig.json

输入以下内容

{

    "compilerOptions": {

      "experimentalDecorators": true,

      "emitDecoratorMetadata": true,

      "lib": ["dom","es2016"],

      "target": "es5"

    },

    "include": ["./src/**/*"] 

}

然后就可以使用了

我们新建一个组件MEditor,上代码

<template>
  <div>
    <div ref="editor" style="text-align:left">
    </div>
  </div>
</template>

<script>
  import E from 'wangeditor' //引入编辑器

  import {
    uploadPicture
  } from "@/api/resume/briefIntroduction";//图片上传方法
  import {
    getToken
  } from "@/utils/auth";//获取用户验证token
  export default {
    name: "MEditor",
    props:{
      /*编辑器的内容*/
      value: {
          type: String
      },
    },
    data: function() {
      return {
        editor:null,
        Title: '',
        Content: this.value,
      }
    },
    mounted: function() {
      let That = this;
      this.editor = new E(this.$refs.editor);
      this.editor.config.placeholder = ''
        //图片上传数量限制
      this.editor.config.uploadImgMaxLength=1;
        //自定义图片上传方法
      this.editor.config.customUploadImg=function(resultFiles, insertImgFn) {
        let data = new FormData;
        data.append('introductionPicture',resultFiles[0]);
          uploadPicture({
			  	Authorization: "Bearer" + getToken(),
			  },data).then(res=>{
            insertImgFn(res.imgUrl)
          });
          // 上传图片,返回结果,将图片插入到编辑器中
      };
      this.editor.config.onchange = function (newHtml) {
            That.$emit('change',newHtml)
      };//组件内容改变,将文本返回到父组件
      this.editor.create();
      this.editor.txt.html(That.Content);//初始化编辑器内文本内容
    },
    watch:{
      value: {//监听value的内容,如果发生改变将文本内容重新写入编辑器
      	handler(val) {
      		if (val !== this.Content) {
      			this.Content = val === null ? "" : val;
      			if (this.editor) {
      				this.editor.txt.html(this.Content);
      			}
      		}
      	},
      	immediate: true,
      },
    },
      beforeDestroy() {
        // 销毁编辑器
        this.editor.destroy()
        this.editor = null
      },
  }
</script>

父组件内使用

<MEditor :value="form.briefintroduction" @change="contentChange"></MEditor>

父组件监听编辑器发出的内容改变事件,实现双向绑定,其实可以修改为v-model,具体可以参考vue官方文档。

contentChange(htmlContent){
      this.form.briefintroduction=htmlContent;
    }

最后再打个广告,关注公众号程序猿青空,不定期分享各种优秀文章、学习资源、学习课程,能在未来(因为现在还没啥东西)享受更多福利。