vue2+wangeditor富文本域

效果图

请添加图片描述

安装依赖

npm i @wangeditor/editor @wangeditor/editor-for-vue

初始化

<template>
  <div class="editor-box">
    <Toolbar
      :defaultConfig="toolbarConfig"
      :editor="editor"
      :mode="mode" />
    <Editor
      class="editor-box__textarea"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="onCreated" />
  </div>
</template>
<script>
import {
    
     Toolbar, Editor } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css'
export default {
    
    
  name: 'App',
  components: {
    
    
    Toolbar, Editor
  },
  data() {
    
    
    return {
    
    
      editor: null,
      mode: 'default',
      toolbarConfig: {
    
    },
      editorConfig: {
    
    },
    }
  },
  beforeDestroy() {
    
    
    const editor = this.editor
    if(editor === null) return
    editor.destroy()
  },
  methods: {
    
    
    onCreated(editor) {
    
    
      this.editor = Object.seal(editor)
    }
  }
}
</script>

wangeditor 默认是没有边框的,为了更好的看到富文本域,给容器加一个边框,同时给编辑的文本域高度增加

<style>
.editor-box{
    
    
  border: 1px solid #e5e5e5;
}
.editor-box__textarea{
    
    
  height: 200px;
}
</style>

此时的效果:
在这里插入图片描述

简约模式

如果你觉得功能太多了,想要个更简约的富文本域,可以直接将 mode 设置为 simple,效果图:
在这里插入图片描述

自定义模式

如果 simpledefault 都不能完全满足你的需求,想自定义不显示指定功能,可以通过 toolbarConfig 设置项。

toolbarConfig: {
    
    
	excludeKeys: ['emotion', ...]
}

excludeKeys 里面的 key 就是你设置的不想要展示的功能项,如何获取到这个 key 呢?
控制台 F12 打开审查元素,找到富文本域的页面元素:
在这里插入图片描述
元素的 data-menu-key 的值就是这个 key 值。

图片设置

只允许 base64 方式

这里为了方便,设置图片都必须转成 base64 格式

editorConfig: {
    
    
  placeholder: '请输入内容',
  MENU_CONF: {
    
    
    uploadImage: {
    
    
      server: 'xxx',
      base64LimitSize: 1 * 1024 * 1024, // > 1M 的图片不转成base64
      onBeforeUpload(file) {
    
    
        const keys = Object.keys(file)
        if(file[keys[0]].size / (1024 * 1024) > 1) {
    
    
          alert('图片大小不能超过 1M.')
        }
      }
    }
  }
}
  • base64LimitSize设置最大转换 base64 的图片极限值为 1M
  • 当上传的图片大小 > 1M 时,会走图片服务器,也就是 server,所以 server 必须给个值,为空会报错:服务器地址为空
  • 为了让 > 1M 的图片不走我们设置的虚假服务器地址,设置 onBeforeUpload 方法,判断图片大小,大于 1M 就给出提示

支持图片服务器

暂未涉及,等待补充…

更多配置

更多配置详见于wangEditor中文文档

项目依赖

"@wangeditor/editor": "^5.1.23",
"@wangeditor/editor-for-vue": "^1.0.2",
"vue": "^2.6.14"

项目代码

代码仓库

猜你喜欢

转载自blog.csdn.net/weixin_43443341/article/details/130847759