
富文本组件
wangEditor
官网地址:https://www.wangeditor.com/
VUE3实现
依赖
text
"@wangeditor/editor": "^5.1.23",
"@wangeditor/editor-for-vue": "^5.1.12",
封装的组件,src/components/wangeditor/index.vue
vue
<template>
<div style="border: 1px solid #ccc">
<Toolbar
style="border-bottom: 1px solid #ccc"
:editor="editorRef"
:defaultConfig="toolbarConfig"
:mode="mode"
/>
<Editor
style="height: 500px; overflow-y: hidden;"
v-model="valueHtml"
:defaultConfig="editorConfig"
:mode="mode"
@onCreated="handleCreated"
/>
</div>
</template>
<script>
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeUnmount, ref, shallowRef, onMounted,defineProps,watch } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { imageUpload } from '@/api/upload'
export default {
components: { Editor, Toolbar },
props: {
text: {
default: '',
type: String,
},
},
setup(props) {
// 编辑器实例,必须用 shallowRef
const editorRef = shallowRef()
// 内容 HTML
const valueHtml = ref(props.text)
// 模拟 ajax 异步获取内容
onMounted(() => {
})
watch(() => props.text, newValue => {
console.log(`Value changed to: ${newValue}`);
// 在这里执行你需要的操作
valueHtml.value = newValue
}, {
immediate: true // 可选:如果希望在初始渲染时也触发一次观察器
});
const toolbarConfig = {}
const editorConfig = {
placeholder: '请输入内容...' ,
MENU_CONF: {}
}
//文件上传
editorConfig.MENU_CONF['uploadImage'] = {
// 小于该值就插入 base64 格式(而不上传),默认为 0
base64LimitSize: 5 * 1024, // 5kb
// 单个文件的最大体积限制,默认为 2M
// maxFileSize: 1 * 1024 * 1024, // 1M
// // 最多可上传几个文件,默认为 100
// maxNumberOfFiles: 5,
// 选择文件时的类型限制,默认为 ['image/*'] 。如不想限制,则设置为 []
allowedFileTypes: ['image/*'],
// 自定义上传
async customUpload(file, insertFn) { // 文件上传
const formData = new FormData();
formData.set('file', file)
// 这里根据自己项目封装情况,设置上传地址
let result = await imageUpload(formData)
// 插入到富文本编辑器中,主意这里的三个参数都是必填的,要不然控制台报错:typeError: Cannot read properties of undefined (reading 'replace')
insertFn(result.data.url, result.data.filename, result.data.filename)
}
}
// 组件销毁时,也及时销毁编辑器
onBeforeUnmount(() => {
const editor = editorRef.value
if (editor == null) return
editor.destroy()
})
const handleCreated = (editor) => {
editorRef.value = editor // 记录 editor 实例,重要!
}
return {
editorRef,
valueHtml,
mode: 'default', // 或 'simple'
toolbarConfig,
editorConfig,
handleCreated
};
}
}
</script>
<style scoped>
</style>
调用
vue
<template>
<Wangeditor :text="text" ref="wangeditorRef" />
</template>
<script setup>
import { defineComponent, ref ,provide,defineProps,onBeforeMount, onMounted } from 'vue'
import Wangeditor from '@/components/wangeditor/index.vue'
const wangeditorRef = ref();
//初始化富文本内容
const text = ref('');
// 获取富文本的内容
wangeditorRef.value.valueHtml
</script>
jquery实现
html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Demo</title>
<link
href="https://unpkg.com/@wangeditor/editor@latest/dist/css/style.css"
rel="stylesheet"
/>
<style>
#editor—wrapper {
border: 1px solid #ccc;
z-index: 100; /* 按需定义 */
}
#toolbar-container {
border-bottom: 1px solid #ccc;
}
#editor-container {
height: 500px;
}
</style>
</head>
<body>
<div id="editor—wrapper">
<div id="toolbar-container"><!-- 工具栏 --></div>
<div id="editor-container"><!-- 编辑器 --></div>
</div>
<button onclick="setVal()">设置值</button>
<button onclick="getVal()">获取值</button>
<script src="https://unpkg.com/@wangeditor/editor@latest/dist/index.js"></script>
<script>
const { createEditor, createToolbar } = window.wangEditor
const editorConfig = {
placeholder: 'Type here...',
onChange(editor) {
const html = editor.getHtml()
console.log('editor content', html)
// 也可以同步到 <textarea>
},
MENU_CONF: {}
}
//文件上传
editorConfig.MENU_CONF['uploadImage'] = {
// 小于该值就插入 base64 格式(而不上传),默认为 0
base64LimitSize: 5 * 1024, // 5kb
// 单个文件的最大体积限制,默认为 2M
// maxFileSize: 1 * 1024 * 1024, // 1M
// // 最多可上传几个文件,默认为 100
// maxNumberOfFiles: 5,
// 选择文件时的类型限制,默认为 ['image/*'] 。如不想限制,则设置为 []
allowedFileTypes: ['image/*'],
// 自定义上传
async customUpload(file, insertFn) { // 文件上传
const formData = new FormData();
formData.set('file', file)
// 这里根据自己项目封装情况,设置上传地址
$.ajax({
url: '/admin/upload/file', // 你的服务器端处理上传的URL
type: 'POST', // 请求类型
data: formData, // 发送的数据是FormData对象
contentType: false, // 告诉jQuery不要设置Content-Type请求头
processData: false, // 告诉jQuery不要处理发送的数据
success: function(response) {
// 上传成功后的处理逻辑
console.log('上传成功:', response);
// 插入到富文本编辑器中,主意这里的三个参数都是必填的,要不然控制台报错:typeError: Cannot read properties of undefined (reading 'replace')
insertFn(response.data.url, response.data.filename, response.data.filename)
},
error: function(xhr, status, error) {
// 上传失败后的处理逻辑
console.error('上传失败:', error);
}
});
}
}
const editor = createEditor({
selector: '#editor-container',
html: '<p><br></p >',
config: editorConfig,
mode: 'default', // or 'simple'
})
const toolbarConfig = {}
const toolbar = createToolbar({
editor,
selector: '#toolbar-container',
config: toolbarConfig,
mode: 'default', // or 'simple'
})
function setVal(){
editor.setHtml('xxxxxxxxxxxx')
}
function getVal(){
alert(editor.getHtml())
}
</script>
</body>
</html>
实现自定义粘贴
其实只要你实现了图片上传接口,就默认支持粘贴上传了,不过也是辛苦写出来了,就暂且记录下吧,其实下面的代码没啥用。
js
MENU_CONF: {
customPaste(editor, event){
// event 是 ClipboardEvent 类型,可以拿到粘贴的数据
// 可参考 https://developer.mozilla.org/zh-CN/docs/Web/API/ClipboardEvent
// const html = event.clipboardData.getData('text/html') // 获取粘贴的 html
// const rtf = event.clipboardData.getData('text/rtf') // 获取 rtf 数据(如从 word wsp 复制粘贴)
const text = event.clipboardData.getData('text/plain') // 获取粘贴的纯文本
// 阻止默认的粘贴行为
event.preventDefault()
const clipboardData = event.clipboardData || window.clipboardData
const items = clipboardData.items
// 遍历剪贴板内容
for (let i = 0; i < items.length; i++) {
const item = items[i]
//如果是图片就走上传逻辑
if (item.type.indexOf('image') !== -1) {
event.preventDefault() // 阻止默认粘贴行为
const file = item.getAsFile()
console.log(editor)
// editor.uploadImage(file)
//上传文件 需要自己实现
uploadImage(file).then(imgUrl => {
editor.dangerouslyInsertHtml(`< img src="${imgUrl}" style="max-width:100%;"/>`)
})
}else{
editor.insertText(text)
}
}
return false
}
}
//mock的方法,只不过将文件转成了base64
function uploadImage(file) {
return new Promise(function(resolve, reject) {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function (e) {
resolve(e.target.result);
};
reader.error = function (error) {
reject(error);
}
})
}