vue3中使用富文本

父组件:

<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>

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容