在使用
Tinymce-vue富文本编辑器时,发现右下角的监听字符数量有问题,后面发现tinymce默认的wordcount插件是 “词数统计”,而不是 “字符计数”,而且默认 UI 要点击一下才能切换。

默认显示的富文本
-
这里是 “词数统计”点击后切换 “字符计数”的效果图
默认计数效果
<template>
<div>
<div class="richText">
<!-- 编辑器 -->
<tinymce-editor
ref="editorRef"
:init="config"
placeholder="请输入内容"
v-model:value="form.detail"
/>
</div>
</div>
</template>
<script setup>
import TinymceEditor from '@/components/TinymceEditor/index.vue';
// 富文本编辑器
const editorRef = ref();
// 富文本配置
const config = ref({
height: 280,
plugins: 'wordcount',
toolbar: 'undo redo | bold italic underline | alignleft aligncenter alignright alignjustify | outdent indent',
menubar: 'file edit',
statusbar: false, // 禁用默认状态栏(会隐藏 words)
setup: (editor) => {
// 自定义状态栏显示字符数
editor.on('init', () => {
// 创建一个容器展示字符数
const counter = document.createElement('div');
counter.id = 'custom-char-counter';
counter.style.cssText = `
text-align: right;
font-size: 12px;
color: #888;
padding: 5px 10px 0 0;
`;
editor.getContainer()?.appendChild(counter);
const updateCharCount = () => {
const content = editor.getContent({ format: 'text' }) || '';
const count = content.length;
counter.innerText = `字符数:${count} / 500`;
};
// 初始化显示
updateCharCount();
// 输入时更新
editor.on('input SetContent Paste Undo Redo', updateCharCount);
// 限制最大字符数
editor.on('keydown', (e) => {
const content = editor.getContent({ format: 'text' });
const charCount = content.length;
const isSpecialKey =
e.ctrlKey ||
e.metaKey ||
['Backspace', 'Delete', 'ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'].includes(e.key);
if (charCount >= 500 && !isSpecialKey) {
e.preventDefault(); // 禁止继续输入
}
});
editor.on('paste', (e) => {
e.preventDefault();
const clipboard = e.clipboardData || window.clipboardData;
const pasteText = clipboard.getData('text');
const content = editor.getContent({ format: 'text' }) || '';
const newText = (content + pasteText).slice(0, 500);
editor.setContent(newText);
});
});
}
})
</script>
- 下面是覆盖
Tinymce-vue富文本编辑器默认的wordcount插件统计后的效果
限制工具栏及字符限制.gif

