0


vue中使用wangeditor富文本编辑器

官方文档

项目中要求实现富文本编辑器取编辑内容

这种编辑器有好多选择了wangeditor富文本编辑器

首先根据文档安装

  1. yarn add @wangeditor/editor
  2. # 或者 npm install @wangeditor/editor --save
  3. yarn add @wangeditor/editor-for-vue@next
  4. # 或者 npm install @wangeditor/editor-for-vue@next --save

再按照官方的指引 cv 如下代码

  1. <template>
  2. <div style="border: 1px solid #ccc">
  3. <Toolbar
  4. style="border-bottom: 1px solid #ccc"
  5. :editor="editorRef"
  6. :defaultConfig="toolbarConfig"
  7. :mode="mode"
  8. />
  9. <Editor
  10. style="height: 500px; overflow-y: hidden;"
  11. v-model="valueHtml"
  12. :defaultConfig="editorConfig"
  13. :mode="mode"
  14. @onCreated="handleCreated"
  15. />
  16. </div>
  17. </template>
  18. <script>
  19. import '@wangeditor/editor/dist/css/style.css' // 引入 css
  20. import { onBeforeUnmount, ref, shallowRef, onMounted } from 'vue'
  21. import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
  22. export default {
  23. components: { Editor, Toolbar },
  24. setup() {
  25. // 编辑器实例,必须用 shallowRef
  26. const editorRef = shallowRef()
  27. // 内容 HTML
  28. const valueHtml = ref('<p>hello</p>')
  29. // 模拟 ajax 异步获取内容
  30. onMounted(() => {
  31. setTimeout(() => {
  32. valueHtml.value = '<p>模拟 Ajax 异步设置内容</p>'
  33. }, 1500)
  34. })
  35. const toolbarConfig = {}
  36. const editorConfig = { placeholder: '请输入内容...' }
  37. // 组件销毁时,也及时销毁编辑器
  38. onBeforeUnmount(() => {
  39. const editor = editorRef.value
  40. if (editor == null) return
  41. editor.destroy()
  42. })
  43. const handleCreated = (editor) => {
  44. editorRef.value = editor // 记录 editor 实例,重要!
  45. }
  46. return {
  47. editorRef,
  48. valueHtml,
  49. mode: 'default', //默认模式
  50. mode: 'simple', //简洁模式
  51. toolbarConfig,
  52. editorConfig,
  53. handleCreated
  54. };
  55. }
  56. }
  57. </script>

这个时候编辑器的功能已经实现了 如下图

但是目前为止他还不是我想要的

因为这个编辑器我想让他在弹窗中出现,而且我不需要那么多功能

接着更文档的步子走

文档里面既然有这个那就肯定可以实现

研究一番发现弱国想要怎加或者修改编辑器的功能首先要获取这个功能的key

点击Deom示例

打开控制台,输入toolbar.getConfig().toolbarKeys这个时候就可以看到每个功能的key了

在回个车

就可以看到详细内容了

这个时候只需要回到代码里面添加

  1. toolbarConfig.toolbarKeys = [
  2. // 菜单 key
  3. 'headerSelect',
  4. // 分割线
  5. '|',
  6. // 菜单 key
  7. 'bold',
  8. 'italic',
  9. 'color',
  10. 'justifyLeft',
  11. 'justifyRight',
  12. 'justifyCenter'
  13. // 继续配置其他菜单...
  14. ]

就可以实现你想要的功能了,如下图

我们可通过toolbarKeys: [], 去实现显示哪些菜单,如何排序、分组的功能 通过excludeKeys: []选择去隐藏哪些菜单

最复杂的就是上传图片了,其实这个也很简单

看看文档

一目了然https://www.wangeditor.com/v5/menu-config.html#%E4%B8%8A%E4%BC%A0%E5%9B%BE%E7%89%87return中写上如下代码,需要注意的时上传图片后,后端必须返回url图片的链接,否则编辑器中不会显示图片

  1. editorConfig: {
  2. placeholder: '点击全屏介绍产品吧...',
  3. // autoFocus: false,
  4. // 所有的菜单配置,都要在 MENU_CONF 属性下
  5. MENU_CONF: {
  6. // 配置字号
  7. // fontSize: [... ],
  8. // 图片上传
  9. uploadImage: {
  10. server: '/api/admin/uploade',
  11. fieldName: 'img',
  12. // 单个文件的最大体积限制,默认为 2M
  13. maximgSize: 10 * 1024 * 1024, // 10M
  14. // 最多可上传几个文件,默认为 100
  15. maxNumberOfimgs: 10,
  16. // 选择文件时的类型限制,默认为 ['image/*'] 。如不想限制,则设置为 []
  17. allowedimgTypes: ['image/*'],
  18. // 自定义上传参数,例如传递验证的 token 等。参数会被添加到 formData 中,一起上传到服务端。
  19. meta: {
  20. // token: 'xxx',
  21. // otherKey: 'yyy'
  22. // img:''
  23. },
  24. // 将 meta 拼接到 url 参数中,默认 false
  25. metaWithUrl: false,
  26. // 自定义增加 http header
  27. headers: {
  28. // Accept: 'text/x-json',
  29. // otherKey: 'xxx'
  30. },
  31. // 跨域是否传递 cookie ,默认为 false
  32. withCredentials: true,
  33. // 超时时间,默认为 10 秒
  34. timeout: 10 * 1000, //10 秒
  35. // 上传前
  36. onBeforeUpload(imgs) {
  37. ElMessage({
  38. message: '图片正在上传中,请耐心等待',
  39. grouping: true,
  40. duration: 0,
  41. customClass: 'uploadTip',
  42. iconClass: 'el-icon-loading',
  43. showClose: true
  44. });
  45. return imgs;
  46. },
  47. // 自定义插入图片
  48. customInsert(res, insertFn) {
  49. // 因为自定义插入导致onSuccess与onFailed回调函数不起作用,自己手动处理
  50. // 先关闭等待的ElMessage
  51. ElMessage.closeAll();
  52. if (res.code === 200) {
  53. ElMessage.success({
  54. message: "图片上传成功",
  55. grouping: true,
  56. });
  57. } else {
  58. ElMessage.error({
  59. message: "图片上传失败,请重新尝试",
  60. grouping: true,
  61. });
  62. }
  63. // 从 res 中找到 url alt href ,然后插入图片
  64. insertFn(res.data.url);
  65. // console.log(res, "res.data")
  66. },
  67. // 单个文件上传成功之后
  68. onSuccess(img, res) {
  69. console.log(`${img.name} 上传成功`, res);
  70. },
  71. // 单个文件上传失败
  72. onFailed(img, res) {
  73. console.log(`${img.name} 上传失败`, res);
  74. },
  75. // 上传进度的回调函数
  76. onProgress(progress) {
  77. console.log('progress', progress);
  78. // progress 是 0-100 的数字
  79. },
  80. // 上传错误,或者触发 timeout 超时
  81. onError(img, err, res) {
  82. console.log(`${img.name} 上传出错`, err, res);
  83. }
  84. },

到这里其实基本功能已经实现了,那我们怎么保存,编辑器中的内容呢

需要知道富文本编辑器是所见即所得的文本编辑器,简单来说就是文本上面写的行内样式,那我们该怎样保存这些行内样式呢,在这里我是写成了组件的形式

官方文档中给出

methods中写上

  1. onChange(editor) {
  2. const text = editor.getHtml()
  3. this.$emit('update:content', text)
  4. },

当内容变化是就获取当前行内样式

然后在父组件中监听下

  1. watch: {
  2. "addlist.content"(value) {
  3. // console.log(value, "就是这里")
  4. },

在需要的地方

  1. <!-- 编辑器组件 -->
  2. <editor-all v-model:content="addlist.content" :passSon="addlist.content" />
  3. <!-- 编辑器组件结束 -->

就可以实现需要的功能啦

完整代码

  1. <template>
  2. <div style="border: 1px solid #ccc; margin-top: 10px;z-index:999;width:537px">
  3. <!-- 工具栏 -->
  4. <Toolbar style="border-bottom: 1px solid #ccc" :editor="editor" :defaultConfig="toolbarConfig" />
  5. <!-- 编辑器 -->
  6. <Editor style="height:200px; overflow-y: hidden;" :defaultConfig="editorConfig" v-model="passSon"
  7. @onChange="onChange" @onCreated="onCreated" />
  8. </div>
  9. </template>
  10. <script>
  11. import { ElMessage } from 'element-plus'
  12. import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
  13. export default {
  14. props: {
  15. passSon: ''
  16. },
  17. data() {
  18. return {
  19. editor: null,
  20. toolbarConfig: {
  21. /* 显示哪些菜单,如何排序、分组 */
  22. // toolbarKeys: [],
  23. /* 隐藏哪些菜单 */
  24. excludeKeys: [
  25. // '|',
  26. 'blockquote',
  27. 'fontSize',
  28. 'fontFamily',
  29. 'lineHeight',
  30. 'bulletedList',
  31. 'numberedList',
  32. 'todo',
  33. 'emotion',
  34. 'group-video',
  35. 'group-indent',
  36. 'group-more-style',
  37. 'insertTable',
  38. 'codeBlock',],
  39. },
  40. editorConfig: {
  41. placeholder: '点击全屏介绍产品吧...',
  42. // autoFocus: false,
  43. // 所有的菜单配置,都要在 MENU_CONF 属性下
  44. MENU_CONF: {
  45. // 配置字号
  46. // fontSize: [... ],
  47. // 图片上传
  48. uploadImage: {
  49. server: '/api/admin/uploade',
  50. fieldName: 'img',
  51. // 单个文件的最大体积限制,默认为 2M
  52. maximgSize: 10 * 1024 * 1024, // 10M
  53. // 最多可上传几个文件,默认为 100
  54. maxNumberOfimgs: 10,
  55. // 选择文件时的类型限制,默认为 ['image/*'] 。如不想限制,则设置为 []
  56. allowedimgTypes: ['image/*'],
  57. // 自定义上传参数,例如传递验证的 token 等。参数会被添加到 formData 中,一起上传到服务端。
  58. meta: {
  59. // token: 'xxx',
  60. // otherKey: 'yyy'
  61. // img:''
  62. },
  63. // 将 meta 拼接到 url 参数中,默认 false
  64. metaWithUrl: false,
  65. // 自定义增加 http header
  66. headers: {
  67. // Accept: 'text/x-json',
  68. // otherKey: 'xxx'
  69. },
  70. // 跨域是否传递 cookie ,默认为 false
  71. withCredentials: true,
  72. // 超时时间,默认为 10 秒
  73. timeout: 10 * 1000, //10 秒
  74. // 上传前
  75. onBeforeUpload(imgs) {
  76. ElMessage({
  77. message: '图片正在上传中,请耐心等待',
  78. grouping: true,
  79. duration: 0,
  80. customClass: 'uploadTip',
  81. iconClass: 'el-icon-loading',
  82. showClose: true
  83. });
  84. return imgs;
  85. },
  86. // 自定义插入图片
  87. customInsert(res, insertFn) {
  88. // 因为自定义插入导致onSuccess与onFailed回调函数不起作用,自己手动处理
  89. // 先关闭等待的ElMessage
  90. ElMessage.closeAll();
  91. if (res.code === 200) {
  92. ElMessage.success({
  93. message: "图片上传成功",
  94. grouping: true,
  95. });
  96. } else {
  97. ElMessage.error({
  98. message: "图片上传失败,请重新尝试",
  99. grouping: true,
  100. });
  101. }
  102. // 从 res 中找到 url alt href ,然后插入图片
  103. insertFn(res.data.url);
  104. // console.log(res, "res.data")
  105. },
  106. // 单个文件上传成功之后
  107. onSuccess(img, res) {
  108. console.log(`${img.name} 上传成功`, res);
  109. },
  110. // 单个文件上传失败
  111. onFailed(img, res) {
  112. console.log(`${img.name} 上传失败`, res);
  113. },
  114. // 上传进度的回调函数
  115. onProgress(progress) {
  116. console.log('progress', progress);
  117. // progress 是 0-100 的数字
  118. },
  119. // 上传错误,或者触发 timeout 超时
  120. onError(img, err, res) {
  121. console.log(`${img.name} 上传出错`, err, res);
  122. }
  123. },
  124. }
  125. },
  126. }
  127. },
  128. mounted() {
  129. },
  130. methods: {
  131. onCreated(editor) {
  132. this.editor = Object.seal(editor) // 【注意】一定要用 Object.seal() 否则会报错
  133. },
  134. onChange(editor) {
  135. const text = editor.getHtml()
  136. this.$emit('update:content', text)
  137. },
  138. },
  139. beforeDestroy() {
  140. const editor = this.editor
  141. if (editor == null) return
  142. editor.destroy() // 组件销毁时,及时销毁 editor ,重要!!!
  143. },
  144. components: { Editor, Toolbar },
  145. }
  146. </script>
  147. <style src="@wangeditor/editor/dist/css/style.css">
  148. </style>

ok


本文转载自: https://blog.csdn.net/u014181423/article/details/127937487
版权归原作者 龙腾数据 所有, 如有侵权,请联系我们删除。

“vue中使用wangeditor富文本编辑器”的评论:

还没有评论