在使用
Tinymce-vue富文本編輯器時,發(fā)現(xiàn)右下角的監(jiān)聽字符數(shù)量有問題,后面發(fā)現(xiàn)tinymce默認的wordcount插件是 “詞數(shù)統(tǒng)計”,而不是 “字符計數(shù)”,而且默認 UI 要點擊一下才能切換。

默認顯示的富文本
-
這里是 “詞數(shù)統(tǒng)計”點擊后切換 “字符計數(shù)”的效果圖
默認計數(shù)效果
<template>
<div>
<div class="richText">
<!-- 編輯器 -->
<tinymce-editor
ref="editorRef"
:init="config"
placeholder="請輸入內(nèi)容"
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, // 禁用默認狀態(tài)欄(會隱藏 words)
setup: (editor) => {
// 自定義狀態(tài)欄顯示字符數(shù)
editor.on('init', () => {
// 創(chuàng)建一個容器展示字符數(shù)
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 = `字符數(shù):${count} / 500`;
};
// 初始化顯示
updateCharCount();
// 輸入時更新
editor.on('input SetContent Paste Undo Redo', updateCharCount);
// 限制最大字符數(shù)
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(); // 禁止繼續(xù)輸入
}
});
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插件統(tǒng)計后的效果
限制工具欄及字符限制.gif

