vue3富文本组件使用
时间: 2025-01-19 20:53:33 浏览: 45
### 如何在 Vue 3 中使用富文本编辑器组件
为了实现更复杂的数据输入功能,如创建和编辑数据,在 Vue 3 应用程序中集成一个富文本编辑器是一个不错的选择。对于这一需求,可以考虑采用 `vue-wangeditor` 或者其他类似的库来增强应用的功能。
#### 安装依赖包
首先需要安装对应的 npm 包以便于后续开发工作顺利开展:
```bash
npm install @wangeditor/editor @wangeditor/editor-for-vue
```
#### 富文本编辑器的基本配置与初始化
接着定义一个新的 Vue 组件用于承载这个强大的编辑工具,并完成必要的设置过程[^1]。
```javascript
// 引入 Editor 和 EditorToolbar 的样式文件
import '@wangeditor/editor/dist/css/style.css'
// 引入 editor 和 toolbar 组件
import { createApp } from 'vue'
import App from './App.vue'
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'
const app = createApp(App)
app.component('editor', Editor)
app.component('toolbar', Toolbar)
app.mount('#app')
```
#### 使用自定义组件
最后一步是在模板里声明并运用之前注册过的 `<editor>` 及其配套的 `<toolbar>` 控件,从而让用户能够方便地操作文档内容。
```html
<template>
<div>
<!-- 工具栏 -->
<toolbar :editor="editor" :defaultConfig="toolbarConfig" style="border-bottom: 1px solid #ccc"></toolbar>
<!-- 编辑区 -->
<editor v-model="valueHtml" :defaultConfig="editorConfig" style="height: 500px; overflow-y: hidden;" />
</div>
</template>
<script setup>
import { ref, onBeforeUnmount, shallowRef } from 'vue';
// 编辑器实例,必须用 shallowRef
const editor = shallowRef();
// 内容 HTML
const valueHtml = ref('<p>欢迎使用 <strong>wangEditor</strong>!</p>');
// 配置项
const toolbarConfig = {};
const editorConfig = { placeholder: '请输入内容...' };
onBeforeUnmount(() => {
const editorInstance = editor.value;
if (editorInstance == null) return;
editorInstance.destroy(); // 组件销毁时,及时销毁编辑器
});
</script>
```
通过上述方法可以在 Vue 3 项目里面成功引入一款优秀的所见即所得型在线文字处理插件——WangEditor,进而满足开发者们对于高级别的表单控件的需求。
阅读全文
相关推荐


















