vue移动端富文本vue-quill-editor 自定义上传图片和样式

前言

最近要做个移动端富文本,但是需求比较简单,只需要能够上传图片和实现文字位置自定义
找了蛮多文章都建议使用quill。既然大伙儿都推荐它,想必它是有过人之处的。话不多说,开始代码。
先看下移动端效果图
使用后看到的移动端效果

参考链接

代码

  • ImgText.vue
<template>
  <div class="example">
    <quill-editor
      class="editor"
      ref="myTextEditor"
      :value="content"
      :options="editorOption"
      @change="onEditorChange"
      @blur="onEditorBlur($event)"
      @focus="onEditorFocus($event)"
      @ready="onEditorReady($event)"
    />
  </div>
</template>

<script>
  import dedent from 'dedent' // 能保持字符串的换行位置
  import debounce from 'lodash/debounce' // 防抖
  import { quillEditor } from 'vue-quill-editor'

  // import theme style
  import 'quill/dist/quill.core.css'
  import 'quill/dist/quill.snow.css'

  export default {
    name: 'quill-example-snow',
    components: {
      quillEditor
    },
    data() {
      return {
        editorOption: {
          modules: {
          	// 可以自定义配置,toolbar内的每个二级数组为一个小组模块
          	// 根据需求可以删除不需要的配置
            toolbar: [
              ['bold', 'italic', 'underline', 'strike'],
              ['blockquote', 'code-block'],
              [{ 'header': 1 }, { 'header': 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] }],
              [{ 'font': [] }],
              [{ 'color': [] }, { 'background': [] }],
              [{ 'align': [] }],
              ['clean'],
              ['link', 'image', 'video']
            ]
          }
        },
        content: dedent`<p style="text-align: right">首次要展示的内容</p>`,
      }
    },
    methods: {
      onEditorChange: debounce(function(value) {
        this.content = value.html
      }, 466),
      onEditorBlur(editor) {
        console.log('editor blur!', editor)
      },
      onEditorFocus(editor) {
        console.log('editor focus!', editor)
      },
      onEditorReady(editor) {
        console.log('editor ready!', editor)
      }
    },
    computed: {
      editor() {
        return this.$refs.myTextEditor.quill
      }
    },
    mounted() {
      console.log('this is Quill instance:', this.editor)
    }
  }
</script>

<style lang="scss" scoped>
  .example {
    display: flex;
    flex-direction: column;
    height: 100vh;
  	overflow: hidden;

    .editor {
      height: 80%;
      overflow: hidden;
    }
  }
</style>
  • 根据需求删减toolbar
 // 上传图片要改写成自定义上传到阿里云,默认图片是按照base64的路径
 import handlers from "./handlers.js";

 data() {
   return {
     editorOption: {
       theme: "snow", // 提供了2种主题:snow和bubble,bubble没有工具栏
       placeholder: "请输入图文详情",
       modules: {
         toolbar: {
           container: [["image"], [{ align: [] }]], // 工具栏选项
           handlers: handlers // 事件重写
         }
       }
     }
   };
 }
  • 自定义配置图片上传handlers.js
import uploadImg from "@/request/upload"; 
// uploadImg,这里是自己封装的图片上传到阿里云,导出的一个方法。
// 思路是:返回一个Promise,把上传到阿里云成功的图片结果resolve出来。

const uploadConfig = {
  name: "img", // 必填参数 文件的参数名
  accept: "image/png, image/gif, image/jpeg" // 可选 可上传的图片格式
};

const handlers = {
  image: function() {
    let self = this;
    let fileInput = this.container.querySelector("input.ql-image[type=file]");
    if (fileInput === null) {
      fileInput = document.createElement("input");
      fileInput.setAttribute("type", "file");
      // 设置图片参数名
      if (uploadConfig.name) {
        fileInput.setAttribute("name", uploadConfig.name);
      }
      // 可设置上传图片的格式
      fileInput.setAttribute("accept", uploadConfig.accept);
      fileInput.classList.add("ql-image");
      // 监听选择文件
      fileInput.addEventListener("change", function(e) {
      	// uploadImg是封装好的上传图片方法
        uploadImg(e.target.files[0]).then(res => {
          if (res.code === "000000") {
          	// 后端返回的图片路径
            let url = res.data[0]; 
            // 获取当前图片的index。
            // 【详见文档】(https://quilljs.com/docs/api/#getselection)
            let length = self.quill.getSelection(true).index;
            
            // 图片上传成功后,img的src需要在这里添加
            self.quill.insertEmbed(length, "image", url);
            self.quill.setSelection(length + 1);
          }
          fileInput.value = "";
        });
      });

      this.container.appendChild(fileInput);
    }
    fileInput.click();
  }
};

export default handlers;

  • 类名替换为样式
    • align为什么要处理成style呢?
    • 因为默认返回的是<p class="ql-align-right">测试内容</p>这类,但是配置之后要使用,这种类名存储到服务器,那么使用的地方也必须引入quill的核心样式。对c端来说增加了不必要的依赖。如果能改成<p style="text-align: right">测试内容</p>就完美啦。
methods: {
    onEditorChange: debounce(function(value) {
      this.content = value.html;
      this.onEditorBlur();
    }, 466),
    onEditorBlur() {
    	// 调试发现每次使用水平对齐,都会生成类名:ql-align-xx,这么有规律,直接用正则替换。
      const myreg = /class="ql-align-(?=justify|center|right)/g;
      let newStr = this.content.replace(myreg, 'style="text-align: ');
      
      // newStr就是需求的结果啦
      console.log(newStr) 
    }
}
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
对于vue-quill-editor自定义上传图片,你可以按照以下步骤进行操作: 1. 首先,你需要在你的Vue项目中安装vue-quill-editor依赖包。可以使用npm或者yarn命令来安装: ```bash npm install vue-quill-editor # 或者 yarn add vue-quill-editor ``` 2. 在你需要使用vue-quill-editor的组件中引入依赖: ```vue <template> <div> <quill-editor v-model="content" :options="editorOptions" @image-added="handleImageAdded" ></quill-editor> </div> </template> <script> import { quillEditor } from 'vue-quill-editor' export default { components: { quillEditor }, data() { return { content: '', editorOptions: { // 这里可以配置其他选项 } } }, methods: { handleImageAdded(file) { // 自定义处理上传图片的逻辑 // 这里可以使用AJAX或其他方式将图片上传到服务器,然后将返回的图片地址插入到编辑器中 } } } </script> ``` 在上述代码中,我们通过`@image-added`事件监听图片添加的事件,并触发`handleImageAdded`方法来处理上传图片的逻辑。 3. 实现`handleImageAdded`方法,根据你的需求自定义上传图片的逻辑。你可以使用AJAX或其他方式将图片上传到服务器,并获取返回的图片地址。然后,你可以使用Quill提供的API将图片插入到编辑器中。下面是一个示例: ```javascript methods: { handleImageAdded(file) { const formData = new FormData() formData.append('image', file) // 发送AJAX请求将图片上传到服务器 axios.post('/upload', formData) .then(response => { const imageUrl = response.data.imageUrl // 将图片地址插入到编辑器中 const range = this.$refs.editor.quill.getSelection() this.$refs.editor.quill.insertEmbed(range.index, 'image', imageUrl) }) .catch(error => { console.error('上传图片失败', error) }) } } ``` 在上述代码中,我们通过axios库发送了一个POST请求将图片上传到服务器,并获取返回的图片地址。然后,我们使用Quill提供的`insertEmbed`方法将图片地址插入到编辑器中。 请注意,这只是一个示例,具体的上传图片逻辑可能因你的项目需求而有所不同。你需要根据自己的实际情况进行相应的修改。 希望以上信息能对你有所帮助!如果你还有其他问题,请继续提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值