vue使用富文本框

最近的一个vue项目需要用到富文本框,并且有插入图片/修改图片的需求。

需要用到组件:

vue-qull-editor //富文本框组件
quill
quill-image-resize-module //用于拖拽改变图片大小

1 安装:

npm install vue-quill-editor --save
npm install quill --save
npm install quill-image-resize-module --save

2 vue.config.vue中配置

configureWebpack: {
    plugins: [
      new webpack.ProvidePlugin({
        'window.Quill': 'quill/dist/quill.js',
        'Quill': 'quill/dist/quill.js'
      })
    ]
}

在这里插入图片描述

3 使用:

注意!使用前请先解决跨域问题,并封装好上传图片的api文件(此例中的 { file_upload } from ‘@/api/fileDownloadUpload’)

这是我封装的图片上传api,一定要注意配置请求头headers,因为文件是用formdata传给后台的,如果不配置请求头,后台无法获取到数据。
在这里插入图片描述

富文本公用组件
template部分:

<template>
  <div class="quill-editor">
    <!-- 图片上传组件辅助-->
    <i-upload
      class="avatar-uploader"
      action="no"
      v-show="false"
      name="img"
      :format="['jpg', 'jpeg', 'png']"
      :headers="header"
      :show-file-list="false"
      :on-error="uploadError"
      :before-upload="beforeUpload"
    ></i-upload>

    <quill-editor
      class="editor"
      v-model="content"
      ref="myQuillEditor"
      :options="editorOption"
      @blur="onEditorBlur($event)"
      @focus="onEditorFocus($event)"
      @change="onEditorChange($event)"
    ></quill-editor>
  </div>
</template>

js部分:

// 工具栏配置
const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
  ['blockquote', 'code-block'], // 引用  代码块
  [{ header: 1 }, { header: 2 }], // 1、2 级标题
  [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表
  [{ script: 'sub' }, { script: 'super' }], // 上标/下标
  [{ indent: '-1' }, { indent: '+1' }], // 缩进
  // [{'direction': 'rtl'}],                         // 文本方向
  [{ size: ['small', false, 'large', 'huge'] }], // 字体大小
  [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题
  [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色
  [{ font: [] }], // 字体种类
  [{ align: [] }], // 对齐方式
  ['clean'], // 清除文本格式
  ['link', 'image', 'video'] // 链接、图片、视频
]
import Quill from 'quill'
import 'quill/dist/quill.snow.css' 
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
//quill图片可拖拽改变大小
import imageResize from 'quill-image-resize-module'
Quill.register('modules/imageResize', imageResize)
//图片上传的api
import { file_upload } from '@/api/fileDownloadUpload'

export default {
  name: 'QuillEditor',
  props: {
    /*编辑器的内容*/
    value: {
      type: String,
      default: ''
    },
    /*图片大小*/
    maxSize: {
      type: Number,
      default: 4000 //kb
    }
  },
  components: {
    quillEditor
  },
  data() {
    return {
      header: {
        // token: sessionStorage.token
      }, // 有的图片服务器要求请求头需要有token
      content: this.value,
      quillUpdateImg: false, // 根据图片上传状态来确定是否显示loading动画,刚开始是false,不显示
      editorOption: {
        theme: 'snow', // or 'bubble'
        placeholder: '您想说点什么?',
        modules: {
          imageResize: {
            //添加
            displayStyles: {
              //添加
              backgroundColor: 'black',
              border: 'none',
              color: 'white'
            },
            modules: ['Resize', 'DisplaySize', 'Toolbar'] //添加
          },
          // imageResize: {},
          toolbar: {
            container: toolbarOptions,
            // container: '#toolbar',
            handlers: {
              image: function(value) {
                if (value) {
                  // 触发input框选择图片文件
                  document.querySelector('.avatar-uploader input').click()
                } else {
                  this.quill.format('image', false)
                }
              },
              link: function(value) {
                if (value) {
                  let href = prompt('请输入url')
                  this.quill.format('link', href)
                } else {
                  this.quill.format('link', false)
                }
              }
            }
          }
        }
      }
    }
  },
  mounted() {},
  watch: {
    value: {
      immediate: true,
      handler(newVal) {
        this.content = newVal
      }
    }
  },
  methods: {
    onEditorBlur() {
      //失去焦点事件
    },
    onEditorFocus() {
      //获得焦点事件
    },
    onEditorChange() {
      //内容改变事件
      this.$emit('on-editor', this.content)
    },
    // 清空
    onClearContent() {
      this.content = ''
      this.$emit('on-editor', this.content)
    },
    // 富文本图片上传前
    beforeUpload(file) {
      // 显示loading动画
      this.quillUpdateImg = true
      let formData = new FormData()
      formData.append('file', file)
      formData.append('fileType', 'topicImg')
      formData.append('relationId', 'topicImgId')
      this.uploadFile(formData)
      return false
    },
    async uploadFile(formData) {
      try {
        await file_upload(formData).then(res => {
          // 获取富文本组件实例
          let quill = this.$refs.myQuillEditor.quill
          if (res && res.code === 200000) {
            let length = quill.getSelection().index
            // 插入图片  res.data为服务器返回的图片地址,如果路径不完整,还需要自己拼接服务器端口号,不然图片无法显示出来
            //`${process.env.VUE_APP_BASE_URL}/file/download?filePath=${res.data}&isOnLine=true`
            quill.insertEmbed(length, 'image', `${res.data}`)
            // 调整光标到最后
            quill.setSelection(length + 1)
          } else {
            this.$Message.error('图片插入失败')
          }
          this.quillUpdateImg = false
        })
      } catch (e) {
        console.log(e)
        // loading动画消失
        this.quillUpdateImg = false
      }
    },
    // 富文本图片上传失败
    uploadError() {
      // loading动画消失
      this.quillUpdateImg = false
      this.$Message.error('图片插入失败')
    }
  }
}

4 多个富文本

很多时候一个页面需要用到两个甚至更多的编辑器,例如增加和修改的时候。这时我们不能多次使用同一个富文本组件,必须另外重新写一个,并且类名/方法名/ref统统重新命名。
如果使用同一个富文本组件,新增的时候 编辑图片是没有问题的,但是在修改的时候 编辑图片就会报错,如下:
在这里插入图片描述

5 当用v-html渲染富文本编辑的内容时,很可能会样式丢失

解决办法:加上插件自带的 ql-editor 类
在这里插入图片描述

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值