安装
npm i wangeditor
使用
<script setup>
import { ElFormItem } from 'element-plus';
import { reactive, toRefs, ref, onBeforeUnmount, onMounted, nextTick } from 'vue';
import WangEditor from 'wangeditor';
const props = defineProps({
echoValue: {
type: Object,
},
});
const { echoValue } = toRefs(props);
const emit = defineEmits(['handleEditorInfo', 'handleFormRefClear']);
let instance;
const editor = ref(null);
const TiLength = ref(0);
const content = reactive({
html: '',
text: '',
});
onMounted(() => {
nextTick(() => {
setTimeout(() => {
wangEditor_box();
if (Object.keys(echoValue.value).length) {
instance.txt.html('');
instance.txt.html(echoValue.value.content);
}
}, 0);
});
});
// 判断富文本编辑器输入是否为空或回车
const getText = (str) => {
return str
.replace(/<[^<p>]+>/g, '') // 将所有<p>标签 replace ''
.replace(/<[</p>$]+>/g, '') // 将所有</p>标签 replace ''
.replace(/ /gi, '') // 将所有 空格 replace ''
.replace(/<[^<br/>]+>/g, ''); // 将所有 换行符 replace ''
};
const isNull = (str) => {
if (str == '') return true;
var regu = '^[ ]+$';
var re = new RegExp(regu);
return re.test(str);
};
const wangEditor_box = () => {
instance = new WangEditor(editor.value);
// 隐藏“网络图片”tab
// instance.config.showLinkImg = false;
// instance.config.uploadImgShowBase64 = true;
instance.config.menus = [
'head', //标题
'bold', //字体加粗
'fontSize', //字号
'fontName', //字体
'italic', //斜体
'underline', //下划线
'strikeThrough', //删除线
'indent',
'lineHeight',
'foreColor', //字体颜色
'backColor', //背景颜色
// "link", //插入链接
'list', //列表
// 'todo',//代办事项
'justify', //对齐方式
// 'quote',// 引用
// "emoticon", //表情
// 'image', //插入图片
// 'video',//插入视频
// 'table',//插入表格
// "code", //插入代码
// 'splitLine',
'undo', //撤销
'redo', //恢复
];
Object.assign(instance.config, {
onchange() {
var reg = /<[^<>]+>/g; //去标签
var value = instance.txt.html().replace(reg, '');
value = value.replace(/ /gi, '');
TiLength.value = value.length;
let text = getText(value);
if (!isNull(text)) {
if (TiLength.value < 10000000 || TiLength.value == 10000000) {
content.html = instance.txt.html();
emit('handleEditorInfo', content.html);
} else {
nextTick(() => {
instance.txt.html(content.html);
});
return false;
}
} else {
emit('handleEditorInfo', '');
}
emit('handleFormRefClear', true);
},
});
instance.create();
};
onBeforeUnmount(() => {
instance.destroy();
instance = null;
});
</script>
<template>
<div class="editor_box_style">
<ElFormItem label="文件内容" class="remark" prop="content">
<div ref="editor" class="editor_style" />
</ElFormItem>
<div>
<span class="wordNumber">{{ TiLength }}/10000000</span>
</div>
</div>
</template>
<style scoped lang="scss">
.editor_box_style {
position: relative;
.wordNumber {
color: #909399;
background: #fff;
text-align: right;
z-index: 99999;
right: 20px;
bottom: 10px;
font-size: 12px;
position: absolute;
}
.editor_style {
width: 660px;
}
}
</style>