tiptap CharacterCount扩展将允许的字符数限制为指定的长度,并能够返回字符和单词的数量,中文文字数量统计不准确,需要自己改进。
npm install @tiptap/extension-character-count
limit 允许输入的字符数量,默认为null不限制。
CharacterCount.configure({
limit: 240,
})
mode 默认textSize统计字符,也可以是nodeSize节点数量。
CharacterCount.configure({
mode: 'nodeSize',
})
characters 获取文档的字符数量。
editor.storage.characterCount.characters()
// 获取指定节点类型的数量
editor.storage.characterCount.characters({ node: someCustomNode })
// 根据 textSize、nodeSize 数量
editor.storage.characterCount.characters({ mode: 'nodeSize' })
words 获取单词数量不支持中文。
editor.storage.characterCount.words()
// 获取指定节点的单词数量
editor.storage.characterCount.words({ node: someCustomNode })
Vue 例子
React 例子
React CSS
<template>
<div>
<editor-content :editor="editor" />
<div v-if="editor">
{{ editor.storage.characterCount.characters() }}/{{ limit }} characters
<br>
{{ editor.storage.characterCount.words() }} words
</div>
</div>
</template>
<script>
import CharacterCount from '@tiptap/extension-character-count'
import Document from '@tiptap/extension-document'
import Paragraph from '@tiptap/extension-paragraph'
import Text from '@tiptap/extension-text'
import { Editor, EditorContent } from '@tiptap/vue-3'
export default {
components: {
EditorContent,
},
data() {
return {
editor: null,
limit: 280,
}
},
mounted() {
this.editor = new Editor({
extensions: [
Document,
Paragraph,
Text,
CharacterCount.configure({
limit: this.limit,
}),
],
content: `
<p>
Let‘s make sure people can’t write more than 280 characters. I bet you could build one of the biggest social networks on that idea.
</p>
`,
})
},
beforeUnmount() {
this.editor.destroy()
},
}
</script>
<style>
/* Basic editor styles */
.ProseMirror {
> * + * {
margin-top: 0.75em;
}
}
.character-count {
margin-top: 1rem;
color: #868e96;
}
</style>
import './styles.scss'
import CharacterCount from '@tiptap/extension-character-count'
import Document from '@tiptap/extension-document'
import Paragraph from '@tiptap/extension-paragraph'
import Text from '@tiptap/extension-text'
import { EditorContent, useEditor } from '@tiptap/react'
import React from 'react'
const limit = 280
export default () => {
const editor = useEditor({
extensions: [
Document,
Paragraph,
Text,
CharacterCount.configure({
limit,
}),
],
content: `
<p>
Let‘s make sure people can’t write more than 280 characters. I bet you could build one of the biggest social networks on that idea.
</p>
`,
})
if (!editor) {
return null
}
return (
<div>
<EditorContent editor={editor} />
<div className="character-count">
{editor.storage.characterCount.characters()}/{limit} characters
<br />
{editor.storage.characterCount.words()} words
</div>
</div>
)
}
/* Basic editor styles */
.ProseMirror {
> * + * {
margin-top: 0.75em;
}
}
.character-count {
color: #868e96;
margin-top: 1rem;
}
本教程Demo的源码点击这里下载,Tiptap Demo,下载完成后运行npm i初始化依赖包。