安装 pnpm install quill
封装组件 QuillEditor.vue
<template>
<div>
<div ref="editor" class="quill-editor"></div>
</div>
</template>
<script lang="ts" setup>
import { ref, onMounted, defineExpose } from 'vue';
import Quill from 'quill';
import 'quill/dist/quill.snow.css'; // 引入样式
import learnApi from '@/api/learn';
const editor = ref<HTMLElement | null>(null);
let quill: Quill | null = null
const props = defineProps({
content: String,
});
onMounted(() => {
if (editor.value) {
quill = new Quill(editor.value, {
theme: 'snow',
modules: {
toolbar:
{
container:[
[{ header: [1, 2, false] }],
['bold', 'italic', 'underline'],
[{ size: ['small', 'normal', 'large', 'huge'] }],
['code-block', 'link'],
['image'],
['clean'],
],
handlers: {
image: () => {
handleImageUpload()
}
}
}
},
});
if (props.content) {//通过方法直接渲染页面的内容
quill.root.innerHTML = props.content;
}
}
});
const handleImageUpload = () => {
const input = document.createElement('input');
input.setAttribute('type', 'file');
input.setAttribute('accept', 'image/*');
input.click(); // 触发文件选择
input.onchange = async (event: Event) => {
const file = (event.target as HTMLInputElement).files?.[0];
if (file) {
quill?.focus(); // 使编辑器获得焦点
const imageUrl = await uploadImage(file); // 等待上传并获取 URL
try {
const range = quill?.getSelection(true); // 获取选择范围
if (range) {
quill?.insertEmbed(range.index, 'image', imageUrl); // 在末尾插入图片
} else {
const index:any = quill?.getLength(); // 获取末尾位置
quill?.insertEmbed(index, 'image', imageUrl); // 在末尾插入图片
}
} catch (error) {
console.error('上传图片失败:', error);
}
}
};
};
const getContent = () => {
return quill?.root.innerHTML; // 或者 quill?.getText() 获取纯文本
};
defineExpose({ getContent });
const uploadImage = async (file: File) => {
const data = {
upload_file: file,
};
const response = await learnApi.uploadFile(data); // 替换为你的上传接口
return response.data.fileUrl; // 返回图片 URL
};
</script>
<style lang="less" scoped>
.quill-editor {
height: 300px; /* 编辑器高度 */
}
</style>
使用组件
<QuillEditor :content="ruleForm.content" ref="editor"></QuillEditor>
获取富文本框里的内容
const editor:any = ref(null);
const getEditorContent = () => {
if (editor.value) {
const content = editor.value.getContent(); // 调用子组件的方法
return content
} else {
console.warn('无法获取编辑器实例');
}
};