vue2引入wangEditor5富文本编辑器

以下为引入wangEditor

<template>
  <div>
    <div class="w-e-for-vue">
      <!-- 工具栏 -->
      <Toolbar
        class="w-e-for-vue-toolbar"
        :editor="editor"
        :defaultConfig="toolbarConfig">
      </Toolbar>

      <!-- 编辑器 -->
      <Editor
        class="w-e-for-vue-editor"
        :style="'height: ' + height"
        :disabled="isDisabled"
        :defaultConfig="editorConfig"
        v-model="content"
        @onChange="onChange"
        @onCreated="onCreated">
      </Editor>
    </div>
  </div>
</template>

<script>
import store from '@/store'
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'
import {baseUrl} from "@/config/env";
import { DomEditor } from '@wangeditor/editor'


export default {
  name: 'wangEditor',
  components: {Editor, Toolbar},
  props: [
    'editorParams'
  ],
  data() {
    return {
      // 富文本编辑器对象
      editor: null,
      // 富文本内容
      content: null,
      // 富文本占位内容
      placeholder: null,
      // 富文本上传图片的地址
      uploadImageUrl: null,
      // 富文本最小高度
      height: '300px',
      // 富文本是否禁用
      isDisabled: false,
      // 工具栏配置
      toolbarConfig: {
        // 显示指定的菜单项
        // toolbarKeys: [],
        // 隐藏指定的菜单项
        excludeKeys: [
          // 隐藏全屏按钮
          "fullScreen"
        ],
      },
      // 编辑器配置
      editorConfig: {
        placeholder: '请输入内容......',
        MENU_CONF: ['uploadImage']
      }
    }
  },
  watch: {
    /**
     * 深度监听富文本参数
     */
    'editorParams': {
      handler: function (newVal, oldVal) {
        if (newVal != null) {
          this.content = newVal.content
          this.editorConfig.placeholder = this.placeholder
          this.uploadImageUrl = newVal.uploadImageUrl
          this.setUploadImageConfig()
          this.height = newVal.height
          this.isDisabled = newVal.isDisabled
        }
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    /**
     * 实例化富文本编辑器
     */
    onCreated(editor) {
      this.editor = Object.seal(editor)
      this.setIsDisabled()
    },
    /**
     * 监听富文本编辑器
     */
    onChange(editor) {
      // console.log('onChange =>', editor.getHtml())
    },
    /**
     * this.editor.getConfig().spellcheck = false
     * 由于在配置中关闭拼写检查,值虽然设置成功,但是依然显示红色波浪线
     * 因此在富文本编辑器组件挂载完成后,操作 Dom 元素设置拼写检查 spellcheck 为假
     */
    async setSpellCheckFasle() {
      let doms = await document.getElementsByClassName('w-e-scroll')
      for (let vo of doms) {
        if (vo) {
          if (vo.children.length > 0) {
            vo.children[0].setAttribute('spellcheck', 'false')
          }
        }
      }
    },
    /**
     * 设置富文本是否禁用
     */
    async setIsDisabled() {
      if (this.editor) {
        this.isDisabled ? (this.editor.disable()) : (this.editor.enable())
      }
    },
    /**
     * 上传图片配置
     */
    setUploadImageConfig() {
      this.editorConfig.placeholder = this.placeholder
      this.editorConfig.MENU_CONF['uploadImage'] = {
        fieldName: 'file', // 文件字段名(后端需要对应的字段), 默认值 'wangeditor-uploaded-image'
        maxFileSize: 6 * 1024 * 1024, // 单个文件的最大体积限制,默认为 2M,此次设置为 6M
        maxNumberOfFiles: 30, // 最多可上传几个文件,默认为 100
        allowedFileTypes: ['image/*'], // 选择文件时的类型限制,默认为 ['image/*'] ,若不想限制,则设置为 []
        meta: {// 自定义上传参数,例如传递验证的 token 等,参数会被添加到 formData 中,一起上传到服务端
          'TENANT-ID': store.getters.userInfo.tenantId,
          Authorization: 'Bearer ' + store.getters.access_token
        },
        metaWithUrl: false, // 将 meta 拼接到 URL 参数中,默认 false
        headers: {// 设置 HTTP 请求头信息
          'TENANT-ID': store.getters.userInfo.tenantId,
          Authorization: 'Bearer ' + store.getters.access_token
        },
        server: this.uploadImageUrl, // 上传图片接口地址
        withCredentials: false, // 跨域是否传递 cookie ,默认为 false
        timeout: 5 * 1000, // 超时时间,默认为 10 秒,此次设置为 5 秒
        // 自定义插入图片
        customInsert(res, insertFn) {
          // 因为自定义插入导致onSuccess与onFailed回调函数不起作用,自己手动处理
          // 注意此处将返回的文件路径拼接出来放入,注意应该是完整地址,res为上传后接口返回的数据
          let file_url = '';
          insertFn(file_url, res.data.fileName, file_url);
        },
        // 上传之前触发
        onBeforeUpload(file) {
          return file
        },
        // 上传进度的回调函数
        onProgress(progress) {
          console.log('progress', progress)
        },
        // 单个文件上传成功之后
        onSuccess(file, res) {
          console.log(`${file.name} 上传成功`, res)
        },
        // 单个文件上传失败
        onFailed(file, res) {
          console.log(`${file.name} 上传失败`, res)
        },
        // 上传错误,或者触发 timeout 超时
        onError(file, err, res) {
          console.log(`${file.name} 上传出错`, err, res)
        }
      }
    },
    /**
     * 获取编辑器文本内容
     */
    getEditorText() {
      const editor = this.editor
      if (editor != null) {
        return editor.getText()
      }
    },
    /**
     * 获取编辑器Html内容
     */
    getEditorHtml() {
      const editor = this.editor
      // 下方三行用来获取编辑器工具栏分组
      // const toolbar = DomEditor.getToolbar(this.editor)
      // const curToolbarConfig = toolbar.getConfig()
      // console.log( curToolbarConfig.toolbarKeys )
      if (editor != null) {
        return editor.getHtml()
      }
    },
    /**
     * 填充编辑器Html内容
     */
    setEditorHtml(html) {
      const editor = this.editor
      if (editor != null) {
        editor.setHtml(html)
      }
    }
  },
  created() {

  },
  mounted() {
    this.setSpellCheckFasle() // 设置拼写检查 spellcheck 为假
    document.activeElement.blur() // 取消富文本自动聚焦且禁止虚拟键盘弹出
  },
  /**
   * 销毁富文本编辑器
   */
  beforeDestroy() {
    const editor = this.editor
    if (editor != null) {
      editor.destroy()
    }
  }
}
</script>

<style src="@wangeditor/editor/dist/css/style.css"></style>

<style lang="less" scoped>
.w-e-full-screen-container {
  z-index: 99;
}

.w-e-for-vue {
  margin: 0;
  border: 1px solid #ccc;

  .w-e-for-vue-toolbar {
    border-bottom: 1px solid #ccc;
  }

  .w-e-for-vue-editor {
    height: auto;

    /deep/ .w-e-text-container {

      .w-e-text-placeholder {
        top: 6px;
        color: #666;
      }

      pre {

        code {
          text-shadow: unset;
        }
      }

      p {
        margin: 5px 0;
        font-size: 14px; // 设置编辑器的默认字体大小为14px
      }
    }
  }
}
</style>

封装为wangEdit组件,调用代码

<wang-edit ref="wangEditorRef" v-if="editShow" :editorParams="editorParams"/>
<script>
// 此处改为你自己存放的路径
import WangEdit from "@/components/text-editor/wangEdit";
export default {
  components: {
    WangEdit
  },
  data() {
    return {
    	editShow: false,
    	editorParams: {
	        content: '', // 富文本内容
	        placeholder: '请填写内容', // 富文本占位内容
	        uploadImageUrl: '/file', // 富文本上传图片的地址
	        height: document.documentElement.clientHeight, // 富文本最小高度
	        isDisabled: false // 富文本是否禁用
      	},
    }
  },
  methods: {
  	setHtml(html){
      // 回显富文本框中内容
      let _this = this;
      this.$nextTick(() => {
        // 此处用来解决富文本编辑器未完全加载的问题
        setTimeout(()=>{
          _this.$refs.wangEditorRef.setEditorHtml(html);
        },200)
      })
    },
    getHtml() {
    	this.$refs.wangEditorRef.getEditorHtml();
    }
  }
}
</script>
  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值