- 使用第三方富文本编辑器库(例如Quill):
首先,安装并导入所选择的富文本编辑器库,并在setup
函数中创建一个可响应的数据,用于保存富文本编辑器的内容。接下来,将该数据绑定到富文本编辑器组件,并在模板中显示其内容。
<template>
<div>
<quill-editor v-model="editorContent"></quill-editor>
<div v-html="editorContent"></div>
</div>
</template>
<script>
import { ref } from 'vue';
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import Quill from 'quill';
export default {
setup() {
const editorContent = ref('');
// 初始化富文本编辑器
const quill = new Quill('#quill-editor', {
// 配置选项
});
// 监听内容变化
quill.on('text-change', () => {
editorContent.value = quill.root.innerHTML;
});
return { editorContent };
},
};
</script>
在上面的代码中,我们使用了quill-editor
组件作为富文本编辑器,并绑定了editorContent
数据。在页面上展示富文本编辑器的内容时,我们使用了v-html
指令来渲染富文本的HTML内容。
- 使用
contentEditable
属性:
首先,在模板中创建一个具有contentEditable
属性的元素,例如<div>
,并通过ref
创建一个对该元素的引用。在setup
函数中,你可以监听富文本编辑器传递的值的变化,并将其赋值给content
数据。最后,使用插值将content
的值展示在具有contentEditable
属性的元素内。
<template>
<div>
<div ref="editable" contenteditable="true"></div>
<div>{{ content }}</div>
</div>
</template>
<script>
import { ref, onMounted } from 'vue';
export default {
setup() {
const editable = ref(null);
const content = ref('');
onMounted(() => {
// 模拟富文本编辑器传递的值
const editorValue = '<strong>Content from editor</strong>';
content.value = editorValue;
editable.value.innerHTML = editorValue;
});
return { editable, content };
},
};
</script>
在上面的代码中,我们使用了contenteditable="true"
来表示元素可以进行编辑。在onMounted
钩子中,我们模拟了富文本编辑器传递的值,并将其赋值给content
数据,并将其渲染在具有contentEditable
属性的元素内。