Vue2 vue-editor不使用image-added handler如何获取Editor和cursorLocation
实现方案
vue-editor 底层封装了 Quill 编辑器,你可以直接通过绑定的ref获取 Quill 实例,再配合 Quill 自带的选区 API 拿到光标位置,不需要依赖image-added事件。
具体实现步骤
- 存储光标位置:可以通过编辑器的
selection-change事件实时存储光标位置,也可以在点击外部按钮打开图片模态框前主动获取当前光标位置,避免编辑器失焦后光标位置丢失。 - 插入图片逻辑:拿到选中的图片URL后,直接调用 Quill 实例的
insertEmbed方法即可在指定位置插入图片。
完整代码示例
模板部分
<!-- vue-editor 配置 --> <vue-editor class="editor" v-model="blogContent" :editor-toolbar="customToolbar" ref="editor" @selection-change="handleSelectionChange" /> <!-- 外部触发按钮 --> <button @click="openImageModal">插入图片</button>
JS 逻辑部分
export default { data() { return { blogContent: '', customToolbar: [ /* 你的工具栏配置,记得移除image项隐藏自带的图片按钮 */ ], currentCursorPos: 0 // 存储光标插入位置 } }, methods: { // 实时更新光标位置 handleSelectionChange(range) { if (range) { this.currentCursorPos = range.index } }, // 打开图片选择模态框 openImageModal() { const quill = this.$refs.editor.quill const currentRange = quill.getSelection() if (!currentRange) { alert('请先点击编辑器确定图片插入位置') return } // 同步最新光标位置 this.currentCursorPos = currentRange.index // 这里写你打开图片模态框的原有逻辑 }, // 选中图片后执行插入 insertSelectedImage(imageUrl) { const quill = this.$refs.editor.quill // 在存储的光标位置插入图片 quill.insertEmbed(this.currentCursorPos, 'image', imageUrl) // 插入完成后将光标移动到图片后方,方便后续输入 quill.setSelection(this.currentCursorPos + 1) // 这里写你关闭图片模态框的原有逻辑 } } }
提示:如果使用Vue3 composition API,只需要把ref的获取方式替换为composition API的写法即可,核心API调用逻辑完全一致。
内容的提问来源于stack exchange,提问作者Shubhang Chourasia
相关产品推荐
相关产品推荐

