父组件:
<RichTextEditor v-model="params.remark" ></RichTextEditor>
子组件:
<template>
<div class="rich-text-editor">
<div ref="editorContainer" style="height: 600px;"></div>
</div>
</template>
<script setup>
import { onMounted, ref, watch } from 'vue';
import Quill from 'quill';
import 'quill/dist/quill.snow.css'; // 引入默认样式
// 定义props
const props = defineProps({
modelValue: {
type: String,
default: ''
}
});
// 定义emits
const emit = defineEmits(['update:modelValue']);
// 创建一个引用,用于挂载Quill编辑器
const editorContainer = ref(null);
let quillInstance = null;
onMounted(() => {
// 初始化Quill编辑器
quillInstance = new Quill(editorContainer.value, {
theme: 'snow',
placeholder: '在这里输入...'
});
// 监听内容变化,并更新父组件的数据
quillInstance.on('text-change', () => {
emit('update:modelValue', quillInstance.root.innerHTML);
});
// 设置初始内容
// if (props.modelValue) {
// quillInstance.pasteHTML(props.modelValue);
// }
});
// 监听modelValue的变化,同步到Quill编辑器
watch(() => props.modelValue, (newValue) => {
// if (newValue !== quillInstance.root.innerHTML) {
// quillInstance.pasteHTML(newValue);
// }
if (quillInstance && newValue !== quillInstance.root.innerHTML) {
quillInstance.root.innerHTML = newValue;
}
});
</script>
<style scoped>
.rich-text-editor {
width: 100%;
}
</style>