LaTeX Math Formulas in Vue with Comark and KaTeX
A Vue and Vite app that renders inline and display LaTeX math in Markdown with the Comark math plugin and KaTeX.
App.vue
<script setup lang="ts">
import { Comark } from '@comark/vue'
import math, { Math } from '@comark/vue/plugins/math'
import 'katex/dist/katex.min.css'
const markdown = `
# Math Formula Examples
## Inline Math
The famous equation $E = mc^2$ relates energy and mass.
The Pythagorean theorem states that $a^2 + b^2 = c^2$.
## Display Math
The quadratic formula:
$$
x = \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a}
$$
## Complex Formulas
The integral:
$$
\\int_0^\\infty e^{-x^2} dx = \\frac{\\sqrt{\\pi}}{2}
$$
Summation:
$$
\\sum_{i=1}^{n} i = \\frac{n(n+1)}{2}
$$
Matrix:
$$
\\begin{pmatrix}
a & b \\\\
c & d
\\end{pmatrix}
$$
`
</script>
<template>
<Suspense>
<Comark
:components="{ math: Math }"
:plugins="[math()]"
>
{{ markdown }}
</Comark>
</Suspense>
</template>
This example renders inline and display LaTeX math expressions in Vue and Vite using @comark/vue/plugins/math and KaTeX.
Features
- Parses
$...$inline formulas and$$...$$display blocks with themathplugin. - Renders parsed expressions through the
MathVue component and KaTeX stylesheet. - Supports fractions, integrals, sums, matrices, Greek letters, subscripts, and superscripts.
Usage
Import the
mathplugin,Mathcomponent, and KaTeX stylesheet:import math, { Math } from '@comark/vue/plugins/math' import 'katex/dist/katex.min.css'Pass the plugin and component to
<Markdown>:<Suspense> <Markdown :plugins="[math()]" :components="{ math: Math }" > {{ content }} </Markdown> </Suspense>Write math expressions in Markdown:
Inline: $E = mc^2$ Display: $$ x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a} $$
Syntax examples
Inline math: wrap an expression in single
$delimiters:The formula $x^2 + y^2 = z^2$ is inline.Display math: wrap a block equation in
$$delimiters:$$ \int_0^\infty e^{-x^2} dx = \frac{\sqrt{\pi}}{2} $$Fractions: use
\frac{numerator}{denominator}:$\frac{a}{b}$Greek letters: use commands such as
\alpha,\beta, and\gamma:$\alpha + \beta = \gamma$Subscripts and superscripts: use
_and^:$x_1^2 + x_2^2$