vue3中,wangEditor富文本组件的使用——.disable()富文本禁用、toolbarKeys配置菜单、shallowRef()创建实例、.destroy()销毁富文本、内容为html格式
效果图
1、页面代码
index.vue
<el-button link size="small" type="primary" @click="compile('write', scope.row)"
v-if="typeName == '协同编写'">
编写
</el-button>
<el-button link size="small" type="primary" @click="compile('see', scope.row)"
v-if="typeName !== '大纲目录'">
查看内容
</el-button>
<wangEditor v-if="showWang" :initValue="textInfo.content" :disabled="wangDisabled"
@getEditorContent="onEditorChange"></wangEditor>
<script lang="ts" setup>
import { ref, inject, onMounted } from 'vue';
const showWang = ref(false)
const wangDisabled = ref(false)
const writeId = ref('')
const textInfo = ref({
content: ''
})
// 列表数据
const getList = () => {
post(constant.ieopCollaborate + '/collaborate/directory/list', { collaborateId: directoryId }).then((res) => {
const { code, data } = res.data
if (code == '200') {
tableData.value = data
if (typeName == '协同编写' || typeName == '多元发布') {
setTimeout(function () {
showWang.value = true
wangDisabled.value = true
seeContent(tableData.value[0].id)
}, 200)
}
}
})
}
onMounted(() => {
getList()
})
// 编写和查看
const compile = (type: any, row: any) => {
setTimeout(function () {
showWang.value = true
}, 200)
console.log(type, row);
writeId.value = row.id
seeContent(row.id)
if (type == 'see') {
showWang.value = false
wangDisabled.value = true
} else {
showWang.value = false
wangDisabled.value = false
}
}
// 富文本
const onEditorChange = (arr: any, html: any) => {
textInfo.value.content = html
}
// 保存/编辑内容
const saveContent = () => {
const params = {
dirId: writeId.value,
content: textInfo.value.content,
}
const url = isEdit.value ? '/collaborate/directory/content/update' : '/collaborate/directory/content/add'
post(constant.ieopCollaborate + url, params).then((res) => {
const { code } = res.data
if (code == '200') {
ElMessage.success('保存成功')
showWang.value = false
setTimeout(function () {
showWang.value = true
seeContent(writeId.value)
}, 200)
}
})
}
// 查看内容
const seeContent = (id: any) => {
post(constant.ieopCollaborate + '/collaborate/directory/content/getByDirId', { dirId: id }).then((res) => {
const { code, data } = res.data
if (code == '200') {
isEdit.value = data?.content
textInfo.value.content = data?.content
}
})
}
</script>
2、引入组件
src\main.ts
/*富文本编辑器*/
app.component('wangEditor', wangEditor);
import wangEditor from "./components/wangEditor/index.vue";
3、组件代码
src\components\wangEditor\index.vue
<template>
<div style="border: 1px solid #ccc" id="wangEditor">
<Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode" />
<Editor style="min-height: 100px; overflow-y: hidden; text-align: left;" v-model="valueHtml"
:defaultConfig="editorConfig" :mode="mode" @onCreated="handleCreated" @onChange="handleChange" />
</div>
</template>
<script setup>
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeUnmount, ref, shallowRef, onMounted, nextTick, watch } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import axios from 'axios'
import { inject } from "vue";
const constant = inject('constant')
// 初始值
const props = defineProps({
initValue: String,
disabled: {
type: Boolean,
default :false,
},
})
const emits = defineEmits(['getEditorContent'])
let mode = ref('default')
// 编辑器实例,必须用 shallowRef
const editorRef = shallowRef()
// 内容 HTML
const valueHtml = ref('')
// 模拟 ajax 异步获取内容
onMounted(() => {
nextTick(() => { // 界面节点更新完以后再修改值。
valueHtml.value = props.initValue
})
})
// 工具栏配置
const toolbarConfig = {
toolbarKeys: [
// 菜单 key
'headerSelect',
'bold', // 加粗
'italic', // 斜体
'through', // 删除线
'underline', // 下划线
'bulletedList', // 无序列表
'numberedList', // 有序列表
'color', // 文字颜色
'insertLink', // 插入链接
'fontSize', // 字体大小
'lineHeight', // 行高
'uploadImage', // 上传图片
'delIndent', // 缩进
'indent', // 增进
'deleteImage',//删除图片
'divider', // 分割线
'insertTable', // 插入表格
'justifyCenter', // 居中对齐
'justifyJustify', // 两端对齐
'justifyLeft', // 左对齐
'justifyRight', // 右对齐
'undo', // 撤销
'redo', // 重做
'clearStyle', // 清除格式
]
}
const editorConfig = {
placeholder: '请输入内容...', // 配置默认提示
// readOnly: true,
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();
// let formData = new FormData();
formData.append('file', file);
formData.append('fileName', file.name)
formData.append('fileType', '0')
formData.append('encrypt', 1)
formData.append('domain', "wangEditor")
formData.append('code', '1'); // 业务标记
formData.append('remark', ""); // 备注
// 这里根据自己项目封装情况,设置上传地址
// axios.defaults.headers.common['Authorization'] = 'Bearer eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VyX2tleSI6IjVhYzc3MDQxLTE3NGItNDEwZC1hOTJlLTVkYzU0YmRhMjllNiIsInVzZXJuYW1lIjoiYWRtaW4ifQ.GhdthjLmw4NP2WV2owYQS70tacRM-pX7NqI7Mo0_j_hatiqtSrqAr0RJC40osRETiQo_dacZcvNqATLsJHL77A'
let result = await axios.post(process.env.VUE_APP_API_HOST + constant.fileUpload + '/uploadImage', formData)
// 插入到富文本编辑器中,主意这里的三个参数都是必填的,要不然控制台报错:typeError: Cannot read properties of undefined (reading 'replace')
insertFn(process.env.VUE_APP_API_HOST + constant.fileUpload + '/previewImage?id=' + result.data.data[0].id, file.name, file.name)
}
}
}
}
// 组件销毁时,也及时销毁编辑器
onBeforeUnmount(() => {
const editor = editorRef.value
if (editor == null) return
editor.destroy()
})
const handleCreated = (editor) => {
editorRef.value = editor // 创建富文本编辑器
if(props.disabled){
editorRef.value.disable() //禁用
}
}
const handleChange = (info) => {
// info.children 数组包含了数据类型和内容,valueHtml.value内容的html格式
emits('getEditorContent', info.children, valueHtml.value)
}
watch(() => props.initValue, (value) => { // 父组件获取初始值
valueHtml.value = value
})
</script>
<style>
.w-e-text-placeholder {
top: 10px;
}
.w-e-text-container {
height: 300px;
}
.w-e-selected-image-container {
max-width: 800px;
}
.w-e-hover-bar .w-e-bar-item:nth-of-type(4),
.w-e-hover-bar .w-e-bar-item:nth-of-type(5) {
display: none;
}
</style>