ietm-math-editor
v0.1.0
Published
基于 Vue 3 + MathLive + KaTeX 的可视化公式编辑器,支持导出/导入内嵌原始数据的矢量 SVG。
Readme
@ietm/math-editor
基于 Vue 3 + MathLive + KaTeX 的可视化公式编辑器,支持导出/导入内嵌原始数据的矢量 SVG,可二次编辑。
安装
npm i @ietm/math-editor vue引入一次样式(全局):
import '@ietm/math-editor/style.css'使用
方式一:全局插件
import { createApp } from 'vue'
import MathEditor from '@ietm/math-editor'
import '@ietm/math-editor/style.css'
createApp(App).use(MathEditor).mount('#app')方式二:局部引入(v-model + ref 命令式接口)
<script setup lang="ts">
import { ref } from 'vue'
import { MathEditor, type MathEditorExpose } from '@ietm/math-editor'
import '@ietm/math-editor/style.css'
const latex = ref('\\frac{a}{b}')
const editor = ref<MathEditorExpose>()
// 导出含原始数据的矢量 SVG
function save() {
editor.value?.exportSvg('formula.svg')
}
// 二次导入:从 SVG 文本还原公式继续编辑
function load(svgText: string) {
editor.value?.importSvgText(svgText)
}
</script>
<template>
<MathEditor
ref="editor"
v-model="latex"
theme="dark"
@change="(v) => console.log(v)"
/>
</template>API
Props
| 名称 | 类型 | 默认值 | 说明 |
| ------------ | --------------------- | -------- | ------------------------ |
| modelValue | string | '' | 公式 LaTeX 源码,支持 v-model |
| theme | 'light' \| 'dark' | - | 受控主题 |
Events
| 名称 | 参数 | 说明 |
| ------------------- | ------------------ | -------------- |
| update:modelValue | (latex: string) | v-model 同步 |
| change | (latex: string) | 公式变化时触发 |
实例方法(通过组件 ref 调用)
| 方法 | 返回值 | 说明 |
| ----------------------------- | ---------- | ------------------------------------ |
| getLatex() | string | 获取当前 LaTeX |
| setLatex(latex) | void | 设置 LaTeX |
| clear() | void | 清空公式 |
| exportSvg(filename?) | void | 导出内嵌原始数据的矢量 SVG 文件 |
| importSvgText(svgText) | boolean | 由 SVG 文本还原公式,成功返回 true |
| focus() | void | 聚焦编辑器 |
工具函数
import { latexToSvg, extractLatexFromSvg, downloadSvg } from '@ietm/math-editor'
const svg = latexToSvg('\\frac{a}{b}') // LaTeX -> 含 metadata 的矢量 SVG 字符串
const latex = extractLatexFromSvg(svgText) // 从 SVG 还原 LaTeX(无数据时返回 null)
downloadSvg(svg!, 'formula.svg') // 触发浏览器下载说明
vue为 peerDependency,需由宿主项目提供;katex/mathlive/mathjax-full已打包进产物,无需额外安装。- 导出的 SVG 为真矢量图(
<path>),并将原始 LaTeX 嵌入<metadata>,因此同一个文件既可在矢量软件中查看,又可再次导入编辑。 importSvgText仅能识别本编辑器导出的(含 metadata 的)SVG。
