1. 安装依赖
首先,需要安装 @vueup/vue-quill
包,这是专为 Vue 3 设计的 Quill 编辑器组件:
bash复制
npm install @vueup/vue-quill
或者使用 yarn:
bash复制
yarn add @vueup/vue-quill
2. 引入样式文件
在项目的入口文件(如 main.js
或 main.ts
)中引入 Quill 的样式文件:
JavaScript复制
import '@vueup/vue-quill/dist/vue-quill.snow.css';
如果需要使用不同的主题样式(如 bubble
主题),可以替换为对应的样式文件。
3. 创建富文本编辑器组件
可以创建一个专门的组件(如 QuillEditor.vue
)来封装 Quill 编辑器:
vue复制
<template>
<quill-editor
v-model="content"
:options="editorOptions"
contentType="html"
@textChange="handleTextChange"
></quill-editor>
</template>
<script setup>
import { QuillEditor } from '@vueup/vue-quill';
import { ref, defineProps, defineEmits } from 'vue';
const props = defineProps({
modelValue: {
type: String,
default: '',
},
});
const emit = defineEmits(['update:modelValue']);
const content = ref(props.modelValue);
const handleTextChange = () => {
emit('update:modelValue', content.value);
};
const editorOptions = {
theme: 'snow',
modules: {
toolbar: [
[{ header: [1, 2, 3, false] }],
['bold', 'italic', 'underline'],
[{ list: 'ordered' }, { list: 'bullet' }],
['link', 'image'],
['clean'],
],
},
};
</script>
4. 在父组件中使用
在父组件中,可以通过 v-model
绑定富文本编辑器的内容:
vue复制
<template>
<div>
<QuillEditor v-model="editorContent" />
<p>编辑器内容:{
{ editorContent }}</p>
</div>
</template>
<script setup>
import { ref } from 'vue';
import QuillEditor from './components/QuillEditor.vue';
const editorContent = ref('<p>初始内容</p>');
</script>