tinymce 富文本编辑器
时间: 2025-01-10 17:51:01 浏览: 71
### 使用 TinyMCE 富文本编辑器
TinyMCE 是一款强大且灵活的所见即所得 (WYSIWYG) 编辑器,适用于各种 Web 应用程序。为了在项目中集成并使用 TinyMCE,需遵循特定步骤来设置环境。
#### 安装依赖包
对于基于 Vue.js 的应用程序,推荐通过 npm 或 yarn 来安装 `tinymce` 和 `@tinymce/tinymce-vue` 组件库:
```bash
npm install tinymce @tinymce/tinymce-vue
```
或者采用 yarn 方式:
```bash
yarn add tinymce @tinymce/tinymce-vue
```
#### 创建组件文件
创建一个新的 Vue 单文件组件用于承载 TinyMCE 实例,在 `<template>` 部分引入官方提供的 Editor 组件标签[^1]。
```html
<template>
<editor v-model="content" :init="editorInit"></editor>
</template>
<script>
import { defineComponent } from 'vue';
import Editor from '@tinymce/tinymce-vue';
export default defineComponent({
components: {
editor: Editor,
},
data() {
return {
content: '',
editorInit: {
height: 500,
menubar: false,
plugins: [
'advlist autolink lists link image charmap print preview anchor',
'searchreplace visualblocks code fullscreen',
'insertdatetime media table paste code help wordcount'
],
toolbar:
'undo redo | formatselect | bold italic backcolor | \
alignleft aligncenter alignright alignjustify | \
bullist numlist outdent indent | removeformat | help'
}
};
}
});
</script>
```
此代码片段展示了如何定义一个简单的 TinyMCE 编辑器实例,并设置了基本的功能按钮和插件列表。
#### 插入图片功能
为了让用户能够上传图片至服务器并在文章内显示,可以在初始化配置中的 `images_upload_handler` 属性指定自定义处理函数。该回调接收二进制数据作为参数,负责将其发送给后端API接口完成实际存储操作后再返回URL地址供前端展示。
```javascript
// 假设这是你的Vue方法之一
methods: {
handleImageUpload(blobInfo, success, failure) {
const formData = new FormData();
formData.append('file', blobInfo.blob(), blobInfo.filename());
fetch('/upload-image-endpoint', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(result => {
if (!result.url) throw Error('No URL returned');
success(result.url);
})
.catch(() => failure('Failed to upload image'));
}
}
```
上述 JavaScript 方法实现了向服务器提交图片的过程,并根据响应结果决定调用成功还是失败回掉函数。
阅读全文
相关推荐













